值给c2
cout<<"\nc3 = c2 - c1;\n"; c3 = c2 - c1; //将c2减去c1赋值给c3
cout<<"\nc3.print();\n"; c3.print(); //打印运算后c3的值 cout<
return 0; } -------------------------------------------------------
Linux 下的Makefile文件内容 ------------------------------------------------------- exe=complex
all: $(exe).o main.o g++ -o $(exe) main.o $(exe).o main.o: main.cpp $(exe).h g++ -g -c $< -o $@ $(exe).o: $(exe).cpp $(exe).h g++ -g -c $< -o $@
.PHONY: clean
clean: rm -rf $(exe) *.o ------------------------------------------------------- 编译程序:make 执行程序:./complex 执行结果: ------------------------------------------------------- COMPLEX c1(1,2); Default Constructing real: 1, image: 2 . //调用默认构造函数创建对象c1,值为:1+2i COMPLEX c2(2); Default Constructing real: 2, image: 0 . //调用默认构造函数创建对象c2,值为:2 COMPLEX c3(c1); Copy Constructing real: 1, image: 2 . //调用拷贝构造函数创建对象c3,值为:1+2i
c3.print(); 1+2i //打印c3原来的值为:1+2i
c1 = c1 + c2 + c3; Default Constructing real: 0, image: 0 . //调用默认构造函数创建临时对象temp1,值为:0 ----- operator x + y start -----. //开始计算c1+c2,这个是调用c1的 “+” 运算符函数 this->real: 1, this->image: 2 . //c1,通过this指针隐式地将c1传递给c1的“+”运算符函数 other.real: 2, other.image: 0 . //c2,将c2传递给c1的“+”运算符函数 temp.real: 3, temp.image: 2 . //相加的结果保存在临时对象temp1中,所以temp1值为:3+2i ----- operator x + y end -----. //c1+c2计算结束,将结果temp1返回调用处 Default Constructing real: 0, image: 0 . //调用默认构造函数创建临时对象temp2,值为:0 ----- operator x + y start -----. //开始计算temp1+c3,这个是调用temp1的 “+” 运算符函数 this->real: 3, this->image: 2 . //temp1,通过this指针隐式地将temp1传递给temp1的“+”运算符函数 other.real: 1, other.image: 2 . //c3,将c3传递给temp1的“+”运算符函数 temp.real: 4, temp.image: 4 . //相加的结果保存在临时对象temp2中,所以temp2值为:4+4i ----- operator x + y end -----. //temp1+ c3计算结束,将结果temp2返回调用处 ----- operator x = y start -----. //开始做赋值运算:c1 = temp2;这里调用c1的“=”运算符函数 other.real: 4, other.image: 4 . //赋值前temp2的值为:4+4i this->real: 1, this->image: 2 . //赋值前c1的值为:1+2i other.real: 4, other.image: 4 . //赋值后temp2的值不变,依然为:4+4i this->real: 4, this->image: 4 . //赋值后c1的值为:4+4i ----- operator x = y end -----. //赋值运算结束,返回当前对象的副本,这里*this就是c1了 Copy Constructing real: 4, image: 4 . //通过拷贝构造函数创建c1的一个副本返回,c1副本的值为:4+4i Destructing real: 4, image: 4 . //析构c1的副本 Destructing real: 4, image: 4 . //析构temp2 Destructing real: 3, image: 2 . //析构temp1
c2 = -c3; Default Constructing real: 0, image: 0 . //调用默认构造函数创建临时对象temp3,值为:0 ----- operator -x start -----. //开始计算 -c3 ,这个是调用c3的 “-” 求负运算符函数 this->real: 1, this->image: 2 . //求负前c3的值为:1+2i temp.real: -1, temp.image: -2 . //求负后将其结果保存在临时对象temp3中,temp3的值为:-1-2i ----- operator -x end -----. // -c3 计算结束,将temp3返回到调用处 ----- operator x = y start -----. //这里是赋值运算:c2 = temp3; 这里调用c2的“=”,过程同上 other.real: -1, other.image: -2 . this->real: 2, this->image: 0 . //赋值前c2的值为:2 other.real: -1, other.image: -2 . this->real: -1, this->image: -2 . //赋值后c2的值为:-1-2i ----- ope |