友元函数实现左移右移操作符重载

注意:输入输出操作符的重载只能依靠友元函数(而不能用成员函数)

ostream& operate<<(ostream &out,Complex &c1)//函数返回值当左值需要返回一个引用
{
out<<“12345,生活真是苦”<<endl;
return out;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用非友元函数实现双目操作符重载,但需要注意一些细节问题。 首先,非友元函数不能直接访问类的私有成员,因此需要将双目操作符重载函数声明为类的成员函数或者将其声明为友元函数。 其次,如果将双目操作符重载函数声明为类的成员函数,则该函数的左操作数将自动绑定到调用该函数的对象上,而右操作数需要作为函数的参数传递。 如果将双目操作符重载函数声明为友元函数,则需要在函数内部访问类的私有成员,可以通过将该函数声明为类的友元函数实现。 以下是一个示例代码,演示了如何使用非友元函数实现双目操作符重载: ```C++ #include <iostream> class Complex { public: Complex(double r = 0.0, double i = 0.0) : real(r), imag(i) {} Complex operator+(const Complex& other) const { return Complex(real + other.real, imag + other.imag); } double getReal() const { return real; } double getImag() const { return imag; } private: double real, imag; }; Complex operator-(const Complex& lhs, const Complex& rhs) { return Complex(lhs.getReal() - rhs.getReal(), lhs.getImag() - rhs.getImag()); } int main() { Complex c1(1.0, 2.0), c2(3.0, 4.0); Complex c3 = c1 + c2; Complex c4 = c1 - c2; std::cout << "c1 + c2 = " << c3.getReal() << " + " << c3.getImag() << "i" << std::endl; std::cout << "c1 - c2 = " << c4.getReal() << " + " << c4.getImag() << "i" << std::endl; return 0; } ``` 在上面的示例代码中,`operator-`函数被声明为一个非友元函数,并且直接访问了类的私有成员。在`main`函数中,我们使用`operator+`和`operator-`来进行复数的加减操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值