#include <iostream>
using namespace std;
class Dog
{
private:
int k;
public: // C++自动创建赋值运算符,
Dog(int kk) : k(kk)
{
cout << "这是构造函数," << endl;
}
Dog(const Dog& dog) : k(dog.k)
{
cout << "这里是拷贝构造函数。" << endl;
}
~Dog()
{
cout << "这里是析构函数," << endl;
}
Dog& operator=(const Dog& r)
{
k = r.k;
cout << "这里是重载赋值运算符。" << endl;
return *this;
}
void print()
{
cout << k << endl;
}
};
int main()
{
int a, b;
a = 10;
b = a; // 赋值运算,也就是把a里面的数据拷贝到b里,
Dog d1(10), d2(20);
Dog d3(d1); // 这里就是拷贝构造函数,
d1.print();
d2.print();
d2 = d1; // 这个是赋值,赋值就是copy
d2.print();
return 0;
}
重载赋值运算符
最新推荐文章于 2022-06-06 19:17:39 发布