C++学習の道(1):コピー構築関数

2353 ワード

//              
#include <iostream>
using namespace std;
class Rectangle
{
public:
    Rectangle(int len=10, int wid=10);
    Rectangle(const Rectangle &p);
    ~Rectangle() { cout<<"Using    constructor"<<endl;};
    void disp()
    { cout<<length<<" "<<width<<endl; }
private:
    int length, width;
};
Rectangle::Rectangle(int len, int wid)
{
    length = len;
    width = wid;
    cout<<"Using normal constructor
"
; } // ① Rectangle::Rectangle(const Rectangle &p) { length = 2*p.length; width = 2*p.width; cout<<"Using copy constructor
"
; } // ② void fun1(Rectangle p) { p.disp(); } // ③ Rectangle fun2() { Rectangle p4(10,30); return p4;} int main() { Rectangle p1(30,40); p1.disp(); Rectangle p2(p1); p2.disp(); Rectangle p3=p1; p3.disp(); fun1(p1); p2=fun2(); p2.disp(); return 0; }