Complex(double r, double i) { r = real; i = imag; } // 參數賦值給成員?反了!
建構子參數 r, i 是**輸入值**,成員變數 real, imag 是**儲存目標**。正確賦值方向為 **成員 = 參數**:
Complex(double r, double i) { real = r; imag = i; }
原寫法導致 real, imag 未初始化 (隨機值),後續 operator double() { return real; } 返回垃圾值,故 d = 2.5 + c1 產生 -9.25596e+061 等異常數字。
class Complex {
public:
Complex() : real(0), imag(0) {}
Complex(double r, double i) : real(r), imag(i) {} // 使用初始化列表
operator double() const { return real; } // 加 const
private:
double real, imag;
};
operator double() 加 const,允許常數物件呼叫。建構子參數賦值方向反向是新手常見錯誤,導致成員未初始化,型別轉換返回垃圾值。修正賦值方向並採用初始化列表即可解決。