发现C++里面有些东西竟然以前完全没有注意过,或者是忘得一干二净......习艺不精
C++中的类如果有定义带某一类型参数的构造函数,那么C++允许你使用“对象 = 参数(构造函数参数同类型)”的形式进行赋值!
只要有合适的构造函数,赋值操作符会调用构造函数将右边构造为类的对象,然后调用合成的拷贝赋值运算符将其赋值给左边:
#include <iostream>
using namespace std;
class A {
public:
int num;
public:
A() {
this->num = 1;
}
A(int num) {
cout << "call construct funcation A(int num)" << endl;
this->num = num;
}
//A &operator=(const A &r) {
// cout << "overload operator =" << endl;
//}
};
int main()
{
A a;
a = 2;
cout << "a.num:" << a.num << endl;
}