1 #include <iostream>
2 #include <cmath>
3
4 using namespace std;
5
6 class complx
7 {
8 private:
9 double real;
10 double imag;
11 public:
12 complx() {}
13 complx(double r, double i): real(r), imag(i) {}
14 complx(complx &c) {real = c.real; imag = c.imag;}
15 complx operator + (const complx &c) const
16 {
17 return complx(real + c.real, imag + c.imag);
18 }
19
20 complx & operator=(const complx & c)
21 {
22 real = c.real;
23 imag = c.imag;
24
25 return *this;
26 }
27
28 friend ostream& operator << (ostream &os, const complx &c);
29
30 double size() const
31 {
32 return sqrt(real*real + imag*imag);
33 }
34 };
35
36 ostream & operator << (ostream &os, const complx &c)
37 {
38 os << "(" << c.real << "," << c.imag << ")";
39
40 return os;
41 }
42
43 const complx & maximum(const complx &c1, const complx &c2)
44 {
45 if (c1.size() > c2.size())
46 {
47 return c1;
48 }
49 else
50 {
51 return c2;
52 }
53 }
54
55
56 int main(void)
57 {
58 complx c1(10, 30);
59 complx c2(13, 25);
60 complx mx = maximum(c1, c2);
61
62 cout << c1 << endl;
63 return 0;
64 }
我不知道這段代碼有什麼問題,它無法通過編譯。只有在註解第14行(複製構造函數)或重寫第17行以返回具體對象時,它纔會通過編譯並正確運行。複製構造函數和返回臨時對象的C++衝突
樣式提示:複製構造函數是一種構造函數,並且也有初始化器列表。 – MSalters