64,637
社区成员
发帖
与我相关
我的任务
分享
class A {
public:
A(int i = 0) {
a = i;
cout << "Consturctor " << a << endl;
}
A(const A&) {
cout << "copy constructor " << endl;
}
A &operator=(const A& ra) {
cout << "= operator " << endl;
return *this;
}
~A() {cout << "Destructor " << a << endl;}
void print(){ cout << a << endl;}
private:
int a;
};
void main()
{
A a1(1), a2(2);
a1 = 5;
}
输出
Consturctor 1
Consturctor 2
Consturctor 5
= operator
Destructor 5
class A {
public:
explicit A(int i = 0) {
a = i;
cout << "Consturctor " << a << endl;
}
A(const A&) {
cout << "copy constructor " << endl;
}
A &operator=(const A& ra) {
cout << "= operator " << endl;
return *this;
}
A &operator=(int m) {
cout << "operator=(int) "<< endl;
return *this;
}
~A() {cout << "Destructor " << a << endl;}
void print(){ cout << a << endl;}
private:
int a;
};
void main()
{
A a1(1), a2(2);
a1 = 5;
a1.print();
a2 = A(10);
a2.print();
}
Consturctor 1
Consturctor 2
operator=(int)
1
我好像明白了,重载operator=(const A&)
(const A&)会调用 A(int)构造函数