2015-07-11 26 views
0

我有一個構造函數和賦值運算符的問題。這是我的代碼:c + +的構造函數和運算符問題

class Class 
{ 
    private: 
     double number1; 
     double number2; 
    public: 
     Class(double, double); 
     Class& operator=(const Class& n); 
} 

Class::Class(double n1 = 0.0, double n2 = 0.0) 
{ 
    this->number1 = n1; 
    this->number2 = n2; 
} 

Class& operator=(const Class& n) 
{ 
    this->number1 = n.number1; 
    this->number2 = n.number2; 
    return *this; 
} 

int main() 
{ 
    Class n1(2., 3.), n2(7., -1.), n3(); 

    n2 = n1; // no problem 
    n3 = n1; // problem 

    return 0; 
} 

您能否讓我欣喜若狂,爲什麼在第二個任務中出現問題?

非常感謝您

編輯:發生以下錯誤:

[Error] assignment of function 'Complex cislo2()' 
[Error] cannot convert 'Complex' to 'Complex()' in assignment 
+0

您遇到什麼樣的問題?編譯錯誤?運行時錯誤?你能否在你的問題中包含錯誤? – MetaFight

+0

我將錯誤添加到原始帖子 – Adam

+0

可能的重複[A a()是什麼意思?](http://stackoverflow.com/questions/17713124/what-does-aa-mean) – amon

回答

2

amon's comment是正確的。

要簡單地解釋它,在你提供的示例代碼:

Class n3(); 

定義功能不帶參數,並通過值返回Class一個實例。

這是C++語法中的一個怪癖。

要解決此錯誤,請在初始化不包含任何構造函數參數的變量時省略空括號對。

+1

你也可以進入使用大括號在> = C++ 11中調用構造函數的習慣。 SomeType t {}; –