2017-10-06 40 views
-1

我想通過使用朋友函數和構造函數來初始化值,但得到錯誤'複雜1 ::複雜1()的未定義引用'可以有人建議我去哪裏錯了。關於使用朋友函數的複數

#include<iostream> 
using namespace std; 

class complex1 
{ 
    float real,img; 
public: 
    complex1(); 
    complex1(float a,float b) 
    { 
     real=a; 
     img=b; 
    } 
    friend complex1 sum(complex1,complex1); 
    friend void display(complex1); 
}; 

complex1 sum(complex1 c1,complex1 c2) 
{ 
    complex1 c3; 
    c3.real=c1.real+c2.real; 
    c3.img=c1.img+c2.img; 
    return c3; 
} 

void display(complex1 c) 
{ 
    cout<<c.real<<"+j"<<c.img; 
} 

int main() 
{ 
    complex1 c1(100.9,200.9); 
    complex1 c2(50.9,50.9); 
    complex1 c=sum(c1,c2); 
    display(c);  //display and sum is given directly because it is friend 
    return 0; 
} 
+0

'complex1 C = SUM(C1,C2);'你'建設與默認的構造函數,它沒有實現C'('complex1() ;'在你的班級中)。然後,你在函數'sum'中使用它。另外,您正在使用'operator1'類型的'complex1'類型,該類型未定義。 – Fureeish

+2

@Fureeish'operator ='不是什麼大不了的,這是由編譯器創建的,因爲不需要定義複製構造函數或析構函數,所以它們不會違反3的規則。 –

+0

@FantasticMrFox正確。儘管對於上下文,它會保留註釋 – Fureeish

回答

0

它與您的friend功能的友善無關。您聲明構造函數:

complex1(); 

但您從未定義它。然後你在complex1 c3;sum中使用它。您需要定義默認的構造函數:

complex1() { 
    //do something 
} 

Here is a live example.