您的位置:首页 > 编程语言 > C语言/C++

实例解释在重载赋值符时复制构造函数和无参构造函数的调用

2016-11-26 13:49 387 查看
#include<iostream>
#include<string>
//#define VNAME(x) #x;
using namespace std;
class Number {
public:
int num;
std::string name;
Number(std::string _name = "nonPara", int n = 0) : num(n), name(_name){
std::cout << "启动无参构造函数:" << name << std::endl;
}
// 在此处补充你的代码
//Number& operator*(Number that){//如果返回Number&,必须用new, 不然Number(xxx,xxx)是在函数体构造的,一旦函数
//	//结束就释放,等到赋值符运算时,传入的number& that是空便会出错
//	return *(new Number("*creature", (this->num)*(that.num)));
//}
Number operator*(Number that){//因为返回Number,其实在乘法的调用过程会有:
//1.Number that 对传入参数其实进行了复制构造
//2.Return 构造了Number creature
//3.返回类型是Number不是Number&,因而会调用复制构造,把creature进行复制后返回,看到分隔符上还是调用了creature->copyconstruction
//即使n1*n2左边没有等于号,也会调用复制构造。

return Number("*creature", (this->num)*(that.num));
}
Number(Number& a){//复制构造函数!!!的参数列表不能有Number类的对象,应该是number的引用
//否则这里的传入参数是必须调用复制构造的,但是确没有在这之前定义复制构造
num = a.num;
name = "copyConstruction";
std::cout << "启动复制构造函数" << a.name << " -> " << this->name << std::endl;

}
Number& operator=(Number& that){//特别注意,重载赋值函数的时候类的成员函数情况
//下应该是返回自己,因为作为成员的操作符函数,第一个传入参数为(被省略)this指针
std::cout << "调用赋值函数:" << this->num << that.name << " -> " << this->name << std::endl;
//从这里可以看到:其实重载赋值函数是先启用无参数构造产生了this这个对象,然后再采用=
this->num = that.num;
return *this;
}
//friend int int(Number a);
operator int(){
return num;
}
};

int main() {
Number n1("n1", 10), n2("n2", 20);
n1*n2;
std::cout << "我是分隔符-------------\n";
Number n3("n3"); n3 = n1*n2;//n2会调用了复制构造
cout << int(n3) << endl;
system("pause");
return 0;
}
//输出结果
//启动无参构造函数:n1
//启动无参构造函数:n2
//启动复制构造函数n2 -> copyConstruction               乘法传入参数类型为Number,不是引用,因此调用复制构造
//启动无参构造函数:*creature                           乘法的return 构造,构造体只存在在函数体内
//启动复制构造函数*creature -> copyConstruction        返回类型为Number,需要复制出来
//我是分隔符-------------
//启动无参构造函数:n3
//启动复制构造函数n2 -> copyConstruction
//启动无参构造函数:*creature
//启动复制构造函数*creature -> copyConstruction
//调用赋值函数:0copyConstruction -> n3
//200
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐