2017-01-05 41 views
1

你好我是學習操作符重載和練習我寫代碼來添加複數。不完整類型無法定義

我似乎我已經正確地完成所有步驟,但在主,當我創建我的類的對象,然後我說

E:\Opp\Practice\ComplexNumbers\main.cpp|9|error: aggregate 'Complex c2' has incomplete type and cannot be defined|

E:\Opp\Practice\ComplexNumbers\main.cpp|9|error: variable 'Complex c2' has initializer but incomplete type|

你可以在我的代碼看看

#include <iostream> 

using namespace std; 

class Complex; 
int main() 
{ 

    Complex c1(10,20),c2(30,40),c3; 
    c3=c1+c2; 
    c3.Display(); 

    return 0; 
} 

class Complex 
{ 

public: 
    Complex(); 
    Complex(int,int); 
    void setReal(int); 
    void setImaginary(int); 
    int getReal(); 
    int getImaginary(); 
    Complex operator + (Complex); 
    void Display(); 

private: 
    int real , imaginary; 
}; 

Complex::Complex() 
{ 
    real = 0; 
    imaginary =0; 
} 


Complex::Complex(int r , int i) 
{ 

    real = r; 
    imaginary =i; 
} 
Complex Complex:: operator +(Complex num1) 
{ 

    Complex temp; 
    temp.real = num1.real + real; 
    temp.imaginary=num1.imaginary + imaginary; 
    return temp; 
} 

void Complex :: Display() 
{ 
    cout << "Real " << real << "Imaginary " << imaginary << endl; 
} 

int Complex ::getReal() 
{ 
    return real; 
} 
int Complex ::getImaginary() 
{ 
    return imaginary; 
} 

void Complex ::setReal(int r) 
{ 
    real = r; 
} 

void Complex::setImaginary(int i) 
{ 
    imaginary = i; 
} 

回答

1

你必須在Complex類聲明後移動int main()。前向宣言在這裏是不夠的。

前向聲明(class Complex;)只讓你操縱指針和引用(它告訴編譯器該類存在,但將在稍後定義)。它不允許你創建對象(這是你的main函數試圖做的事情......這個代碼必須在class Complex {...};聲明之後被編譯)。

+0

是的,它的工作感謝,但請解釋更多... –

+0

我想你寫了這個評論之前,我編輯我的帖子來解釋更多。目前的解釋不夠嗎? – jpo38

+0

是啊謝謝,現在我有你的點上帝保佑你:) –