【问题标题】:I am trying to write friend function for adding 2 complex numbers in C++我正在尝试编写用于在 C++ 中添加 2 个复数的友元函数
【发布时间】:2015-10-04 06:17:57
【问题描述】:

我正在尝试为我的班级测试编写两个复数相加的友元函数。

// 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”的成员

我该如何解决这个问题?

【问题讨论】:

  • 您可以使用运算符重载,而不是使用友元函数 (friendfun)。它将使您的代码更高效、更易读。您也不必面对此类问题。
  • @TanmoyKrishnaDas 如何让代码更高效?
  • 说真的,你不觉得写 c1+c2 (加法的情况下)或 c1+=c2 (相当于他的代码)比调用一个完全正确的朋友函数更有效率和可维护性一样的东西?这不像他在其他类中使用该功能。不必要的朋友功能通常会导致无意的人为错误。在他的代码中,当他可能只想显示加法的结果时,他正在更改 c1 的值(如果他使用运算符重载,他可以通过编写 cout &lt;&lt; (c1+c2).display() &lt;&lt; endl; 来实现)。
  • @TanmoyKrishnaDas 重载的运算符只是函数,没有比它们更高效(这个词在编程上下文中通常被理解的意思)了。此外,有理由更喜欢免费的友元函数而不是重载运算符的方法。
  • 复数有一些非常困难和混乱的操作。如果他尝试使用友元函数来实现这些操作,对他来说将困难百倍。他的代码会变得有问题,并且由于他必须即兴解决这些错误,他的代码将变得更加不稳定和效率低下。因此,总体而言,他的代码最终会变得效率降低。在这样一个小例子中,使用友元函数可能更有效,但在更大的范围内,使用友元函数实现复数的复杂运算是非常不切实际的。

标签: c++ friend-function


【解决方案1】:

当你像这样声明一个友元函数时,它仍然是一个普通的非成员函数,这意味着你把它称为

complex cres = friendfun(c1, c2);

【讨论】:

    【解决方案2】:

    您想添加好友功能。您将不得不使用运算符重载,然后像这样加好友:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-23
      • 2017-11-28
      • 1970-01-01
      • 1970-01-01
      • 2022-01-25
      • 2021-08-25
      • 2021-11-16
      • 2020-02-27
      相关资源
      最近更新 更多