标题:哪里错了,求解,运算符重载
只看楼主
ehszt
Rank: 12Rank: 12Rank: 12
等 级:贵宾
威 望:40
帖 子:1728
专家分:3216
注 册:2015-12-2
结帖率:100%
已结贴  问题点数:20 回复次数:2 
哪里错了,求解,运算符重载
编译通不过
#include <iostream>
using namespace std;
class base
{
    float real,image;
    public:
        base (){}
        base (float x,float y):real(x),image(y){
        }
         base operator + (base ,base );
        void show()
        {
            cout<<real<<" +"<<image<<"i"<<endl;
        }
};

 base base::operator+(base a,base b)
 {
     base c;
     c.real=a.real+b.real;
     c.image=a.image+b.image;
     return c;
 }
 
 main()
 {
     base a(1.2,4.5),b(2.2,5.5);
     base c;
     c=a+b;
     c.show();
 }

[此贴子已经被作者于2019-8-15 19:52编辑过]

搜索更多相关主题的帖子: 运算符重载 base float real image 
2019-08-15 19:03
rjsp
Rank: 20Rank: 20Rank: 20Rank: 20Rank: 20
等 级:版主
威 望:507
帖 子:8890
专家分:53117
注 册:2011-1-18
得分:20 
base base::operator+(base a,base b)
要么去掉一个参数,变为 base base::operator+( base rhs ),即 *this 和 rhs 相加
要么加上friend,变为 friend base base::operator+(base a,base b),即与 *this 没有任何关系

程序代码:
#include <iostream>

class base
{
public:
    base() : real_(), image_()
    {
    }
    base( double real, double image=0.0 ) : real_(real), image_(image)
    {
    }
    friend base operator+( const base& lhs, const base& rhs );
    friend std::ostream& operator<<( std::ostream& os, const base& val );

protected:
    double real_, image_;
};

#include <iomanip>
#include <sstream>
using namespace std;

base operator+( const base& lhs, const base& rhs )
{
    return base( lhs.real_+rhs.real_, lhs.image_+rhs.image_ );
}
std::ostream& operator<<( std::ostream& os, const base& val )
{
    std::ostringstream buf;
    buf.flags( os.flags() );
    buf.imbue( os.getloc() );
    buf.precision( os.precision() );
    buf << val.real_ << setiosflags(ios::showpos) << val.image_ << 'i';
    return os << buf.str();
}

int main( void )
{
    base a(1.2,4.5), b(2.2,5.5);
    base c = a + b;
    cout << c << endl;

    cout << base(-1,-2) << endl;
}

2019-08-16 09:07
ehszt
Rank: 12Rank: 12Rank: 12
等 级:贵宾
威 望:40
帖 子:1728
专家分:3216
注 册:2015-12-2
得分:0 
哦,知道了,谢谢!
2019-08-16 11:28



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-496414-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.019992 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved