我试图在c++中为添加2个复数写朋友函数

I am trying to write friend function for adding 2 complex numbers in C++

本文关键字:2个 函数 朋友 添加 c++      更新时间:2023-10-16

我正在为我的类测试编写朋友函数,用于添加两个复数。

// Example program
 #include <iostream>
 using namespace std;
class complex{
public:
int real;
int imag;
complex():real(0),imag(0){}
complex(int i, int j)
{
    real = i;
    imag = j;
}
void getdata(){
    cout<<"Enter the Real and Imaginary part"<<endl;
    cout<<"Real : ";
    cin>>real;
    cout<<"Imaginary : ";
    cin>>imag;
    cout<<endl;
}
void display(){
    cout<<real<<"+"<<imag<<"i"<<endl;
}
friend complex friendfun(complex&, complex&);
};

complex friendfun(complex&c1,complex&c2){
c1.real=c1.real+c2.real;
c1.imag=c1.imag+c2.imag;
return c1;
}
int main(){
complex c1,c2;
c1.getdata();
c2.getdata();
cout<<"C1 : ";
c1.display();
cout<<"C2 : ";
c2.display();
c1.friendfun(c1,c2);
cout<<"After addition by friend fun"<<endl;
c1.display();
}

我得到了:

49:8:错误:'class complex'没有名为'friendfun'的成员

如何解决这个问题?

当你像这样声明友元函数时,它仍然是一个普通的非成员函数也就是说你把它叫做

complex cres = friendfun(c1, c2);

您想要添加好友功能。您必须使用操作符重载,然后像这样将其设为友元:

#include <iostream>
using namespace std;
class complex
{
    float x, y;
public:
    complex()
    {
    }
    complex(float real, float img)
    {
        x = real;
        y = img;
    }
friend complex operator+(complex,complex);
    void display(void);
};
complex operator+(complex c,complex d)
{
    complex t;
    t.x = d.x + c.x;
    t.y = d.y + t.y;
    return(t);
};
void complex::display(void)
{
    cout << x << "+i" << y << endl;
}


int main()
{
    complex c1, c2, c3;
    c1 = complex(2.5, 3.5);
    c2 = complex(1.5, 5.5);
    c3 = c1 + c2;//c3=opra+(c1,c2)
    cout << "C1:" << endl;
    c1.display();
    cout << "C2:" << endl;
    c2.display();
    cout << "C3:" << endl;
    c3.display();
}