C++ 学习之路(1):拷贝构造函数

// 调用拷贝构造函数的三种情况
#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\n";
}

// 调用①
Rectangle::Rectangle(const Rectangle &p)
{
    length = 2*p.length;
    width = 2*p.width;
    cout<<"Using copy constructor\n";
}

// 调用② 对象作函数参数
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;
}

你可能感兴趣的:(C++学习)