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