Files
BasicsOfComputerSoftwareEng…/OOP/15Exam/3.6.cpp
2023-06-03 14:02:58 +08:00

136 lines
2.7 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#include <iostream>
using namespace std;
class complex { // 复数类声明
public: // 外部接口
complex(double r = 0, double i = 0) {
this->r = r;
this->i = i;
// this->num = ++count;
// cout << "(Num: " << this->num << ")";
cout << "Constructor!";
display();
}
complex(const complex &c) : r(c.r), i(c.i) {
// this->num = ++count;
// cout << "(Num: " << this->num << ")";
cout << "Copy Constructor!";
display();
}
~complex() {
// cout << "(Num: " << this->num << ")";
cout << "Destructor!";
display();
}
complex operator+(complex c1);
void display(); // 输出复数
private:
// static int count;
// int num;
double r; // 复数实部
double i; // 复数虚部
};
complex complex::operator+(complex c2) {
// complex result(r + c2.r, i + c2.i);
// return result;
return complex(r + c2.r, i + c2.i);
// 原文return complex(r + c2.r, i + c2.i),不能编译=_=
}
void complex::display() {
cout << "(" << r << "," << i << ")" << endl;
}
// int complex::count = 0;
int main() { // 主函数
complex c1(3, 2), c2(2, 5), c3;
cout << "c1=";
c1.display();
cout << "c2=";
c2.display();
c3 = c1 + c2;
cout << "c3=c1+c2=";
c3.display();
return 0;
}
// 这个题我愿称之为史上最烂烂题。他的输出与编译器有没有开右值引用优化有很大的关系。
// 中间一些注释掉的代码是我补的,可以帮助理解一下到底是哪个对象在做这些操作。
/*
关闭右值引用优化:
Constructor!(3,2)
Constructor!(2,5)
Constructor!(0,0)
c1=(3,2)
c2=(2,5)
Copy Constructor!(2,5)
Constructor!(5,7)
Copy Constructor!(5,7)
Destructor!(5,7)
Destructor!(5,7)
Destructor!(2,5)
c3=c1+c2=(5,7)
Destructor!(5,7)
Destructor!(2,5)
Destructor!(3,2)
*/
/*
(Num: 1)Constructor!(3,2)
(Num: 2)Constructor!(2,5)
(Num: 3)Constructor!(0,0)
c1=(3,2)
c2=(2,5)
(Num: 4)Copy Constructor!(2,5)
(Num: 5)Constructor!(5,7)
(Num: 6)Copy Constructor!(5,7)
(Num: 5)Destructor!(5,7)
(Num: 6)Destructor!(5,7)
(Num: 4)Destructor!(2,5)
c3=c1+c2=(5,7)
(Num: 6)Destructor!(5,7)
(Num: 2)Destructor!(2,5)
(Num: 1)Destructor!(3,2)
*/
/*
开启右值引用优化:
Constructor!(3,2)
Constructor!(2,5)
Constructor!(0,0)
c1=(3,2)
c2=(2,5)
Copy Constructor!(2,5)
Constructor!(5,7)
Destructor!(5,7)
Destructor!(2,5)
c3=c1+c2=(5,7)
Destructor!(5,7)
Destructor!(2,5)
Destructor!(3,2)
*/
/*
(Num: 1)Constructor!(3,2)
(Num: 2)Constructor!(2,5)
(Num: 3)Constructor!(0,0)
c1=(3,2)
c2=(2,5)
(Num: 4)Copy Constructor!(2,5)
(Num: 5)Constructor!(5,7)
(Num: 5)Destructor!(5,7)
(Num: 4)Destructor!(2,5)
c3=c1+c2=(5,7)
(Num: 5)Destructor!(5,7)
(Num: 2)Destructor!(2,5)
(Num: 1)Destructor!(3,2)
*/