关于使用友元功能的复数

时间:2017-10-06 20:50:00

标签: c++ oop c++11 friend

我试图通过使用友元函数和构造函数来初始化值但是得到错误'对complex1 :: complex1()'的未定义引用来添加2个复数。有人可以建议我哪里出错。

#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;
}

1 个答案:

答案 0 :(得分:0)

它与你friend功能的友善无关。你声明了一个构造函数:

complex1();

但你永远不会定义它。然后,您在complex1 c3;的{​​{1}}中使用它。您需要定义默认构造函数:

sum

Here is a live example.