我试图在c++中为添加2个复数写朋友函数
I am trying to write friend function for adding 2 complex numbers in C++
我正在为我的类测试编写朋友函数,用于添加两个复数。
// 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();
}
相关文章:
- 我需要将多个函数组合为一个函数
- 等待整个 omp 块完成,然后再调用第二个函数
- 如何巧妙地编写两个函数——一个用于检查是否存在解决方案,另一个用于获取所有解决方案
- 我们是否需要为 C++ 中的多个函数初始化多个模板?
- 两个函数模板候选项.将一个参数作为引用后,选择不太专业的模板
- 如何比较两个函数的速度和性能
- 如何在构造器的成员初始值设定项列表中调用两个函数?
- 如何将这两个函数组合成一个实现?
- 将具有相反操作数的两个函数重构为一个
- 如何一次运行3个函数?
- 如何将多个函数重载作为单个参数传递?
- 创建整数的 2D 数组,该数组将使用两个函数用随机数填充矩阵.我做错了什么?
- 尝试通过多个函数移动数组,但遇到了我不知道如何修复的错误
- 在多个函数中使用全局glfw窗口
- 如何在 v8 Javascript 中的多个函数中使用相同的上下文?
- 渲染窗口无法跨多个函数工作
- 具有相同主体的两个函数具有不同的名称
- C++ 通过多个函数传递模板参数
- 何时使用多个函数调用和 QTimer 调用析构函数?
- C++使用第二个函数获取字符数组的长度