T t(2), T t = 2, T t = T(2)三者完全等價
[cpp]
#include <iostream>
#include <ostream>
#include <string>
using namespace std;
class T{
public:
T(){};
T(int t)
{
cout << "復制" << endl;
a = t;
};
T& operator = (const T& t)
{
cout << "賦值" << endl;
a = t.a;
return *this;
}
int a;
};
int main()
{
T t(2);
cout << "------------------"<< endl;
T t1 = 2;
cout << "------------------"<< endl;
T t2 = T(2);
cout << "------------------"<< endl;
T t3;
t3 = t2;
return 0;
}
#include <iostream>
#include <ostream>
#include <string>
using namespace std;
class T{
public:
T(){};
T(int t)
{
cout << "復制" << endl;
a = t;
};
T& operator = (const T& t)
{
cout << "賦值" << endl;
a = t.a;
return *this;
}
int a;
};
int main()
{
T t(2);
cout << "------------------"<< endl;
T t1 = 2;
cout << "------------------"<< endl;
T t2 = T(2);
cout << "------------------"<< endl;
T t3;
t3 = t2;
return 0;
}
輸出結果為:
復制
------------------
復制
------------------
復制
------------------
賦值