加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c/c++ 友元的简单应用

发布时间:2020-12-15 04:55:50 所属栏目:百科 来源:网络整理
导读:友元的简单应用 1,对象 + 对象,或者,对象 + 数字,可以用类的成员函数去重载+号函数,但是,数字 + 对象就不能用类的成员函数去重载+号函数了, 因为编译器会把数字 + 对象翻译成数字.operator+(const 类 对象),因为数字不是类的对象,无法传递给类的成

友元的简单应用

1,对象 + 对象,或者,对象 + 数字,可以用类的成员函数去重载+号函数,但是,数字 + 对象就不能用类的成员函数去重载+号函数了,

因为编译器会把数字 + 对象翻译成数字.operator+(const 类 &对象),因为数字不是类的对象,无法传递给类的成员函数this指针。

用友元去重载:数字 + 对象

2,用友元去重载:>>运算符和<<运算符。

其实用类的成员函数也可以重载<<运算符,但是使用起来比较怪异,不能使用cout << 对象,只能使用对象 << cout。

#include

using namespace std;

class Imaginary{

friend Imaginary operator+(int i,const Imaginary &m);

friend ostream& operator<<(ostream &os,const Imaginary &m);

friend istream& operator>>(istream &is,Imaginary &m);

public:

Imaginary():real(0),imag(0){

cout << "c:" << this << endl;

}

Imaginary(int real,int imag):real(real),imag(imag){

cout << "c:" << this << endl;

}

Imaginary operator+ (const Imaginary &m){

return Imaginary (real + m.real,imag + m.imag);

}

Imaginary operator+ (int i){

return Imaginary(real + i,imag);

}

Imaginary& operator= (const Imaginary &m){

cout << "asign" << endl;

if(this != &m){

real = m.real;

imag = m.imag;

}

return *this;

}

ostream& operator<<(ostream& os){

os << "[" << real << "," << imag << "]";

return os;

}

~Imaginary(){

cout << this << endl;

}

private:

int real;

int imag;

};

Imaginary operator+(int i,const Imaginary &m){

return Imaginary(i + m.real,m.imag);

}

ostream& operator<<(ostream &os,const Imaginary &m){

os << "(" << m.real << "," << m.imag << ")";

return os;

}

istream& operator>>(istream &is,Imaginary &m){

is >> m.real >> m.imag;

return is;

}

int main(){

Imaginary m1(10,20);

Imaginary m2(1,2);

Imaginary m3 = m1 + m2;

Imaginary m4 = m1 + 10;

Imaginary m5 = 20 + m1;

cout << "a" << m5 << "aa" << endl;;

m5 << cout << "bb" << endl;

Imaginary m6;

cin >> m6;

cout << m6 << endl;

return 0;

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读