T t(2), T t = 2, T t = T(2)三者完全等价
#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;
}输出结果为:
复制
------------------
复制
------------------
复制
------------------
赋值
本文通过一个简单的C++程序展示了类T的三种实例化方式:直接初始化、使用整数初始化以及通过函数调用初始化,并解释了每种情况下构造函数与赋值操作符的调用情况。

被折叠的 条评论
为什么被折叠?



