uacs2024

导航

C++复制构造函数、=运算符重载

C++复制构造函数、=运算符重载

#include<iostream>
using namespace std;

class base{
private:
    int x,y;
public:
    base():x(2),y(4)  {cout << "base default constructor" << endl;}
    base(int x,int y):x(x),y(y)  {cout << "base parameter constructor" << endl;}
    ~base()  {cout << "base destructor" << endl;}
    void show()  {cout << x << " " << y << endl;}
    /*base(const base &b){
        x = b.x;y = b.y;
        cout << "base copy constructor" << endl;
    }*/
    /*void operator=(const base &b){
        x = b.x;y = b.y;
        cout << "void operator = " << endl;
    }*/
    base operator=(const base &b){
        cout << "base operator = " << endl;
        return base(b.x,b.y);
    }
};

int main() {
    base b1;
    b1.show();
    base b2 = b1;
    b2.show();
    base b3(b1);
    b3.show();

}

 另一个例子

#include <iostream>
using namespace std;

class base{
private:
    void show()  {cout << "------------" << endl;}
    friend void showOut(base &b);
}

void showOut(base &b)  {b.show();}

int main(){
    //普通的构造函数
    coordinate a(1, 2);
    //拷贝构造函数
    coordinate b = a;
    // =运算符重载函数
    coordinate c;
    c = a;
    a.print();
    b.print();
    c.print();
}

 

posted on 2024-03-27 13:02  ᶜʸᵃⁿ  阅读(1)  评论(0编辑  收藏  举报