09~C++ 运算符重载、友元函数、友元类

一、运算符重载 成员函数与友元函数
1、
重载+ 运算符使用 成员函数
重载- 运算符使用 一般函数

#include <iostream>
using namespace std;
struct Stack {
	//成员函数 重载
	Stack operator+(Stack const& that) const{
		cout <<"operator+ with rhs that" << endl;
		/*return 语句构造匿名对象 拷贝构造*/
		return *this;
	}
	Stack (Stack const& that) {
		cout << "cp constructor" << endl;
	}
	Stack operator=(Stack const& that) {
		cout <<  "operator=" << endl;
	}
	Stack (double rhs) {
		cout <<"double convertor" << endl;
	}
	explicit Stack(void) {
	}
};
/*非成员函数,另一种运算符重载的方法*/
Stack operator- (Stack const& lfs, Stack const& rhs){
	cout << "operator- with rhs that" <<endl;
	/*return 语句 拷贝构造匿名对象*/
	return lfs;
}
 
int main() {
Stack s1;
Stack s2;
/*这里有一个很重要的技巧:返回值的资源一般来讲应该是由编译器进行匿名分配的,但是因为此处为构造函数,返回值内存资源直接指向了s3,因此没有调用两次拷贝构造函数(operator+函数中调用一次)*/
Stack s3 = s2 + s1; //s2.operator+(s1) -> copy constructor
Stack s4 = s2 - s1;//operator-(s2,s1) -> copy constructor


s3  = s2 + s1; //operator+s2.(s1) -> copy constructor -> operator=
//operator-(Stack const& lfs, Stack const& rhs) -> copy constructor -> operator=
s4 = s2 -s1; //operator-(s2,s1) -> operator=

s3 = s2 + 3.3;
//s3 = 3.3 + s2;

s4 = s2 - 3.3;
s4 = 3.3 -s2;

return 0;
}

2、友元
友元 分友元函数,友元类两种

2.1 友元函数可以直接访问类中私有的部分,相当对类的扩展

#include <iostream>
using namespace std;
struct Stack {
	Stack(int item) {
		m_data = item;
	}
	/*这样友元函数可以直接访问 私有成员m_data*/
	friend std::ostream & operator<< (std::ostream& os,  Stack const& rhs);
private:
int m_data;
};

/*ostream 没有实现 operator<<(Stack const& that),
所以只能通过这种方法实现运算符重载,为了直接访问类中的私有成员,需要声明为Stack的友元函数*/
ostream& operator<< (ostream& os, Stack const& rhs) {
	os << rhs.m_data;
	return os;
}
 
int main() {
Stack s1(99);
Stack s2(100);

cout << s1 << endl;
cout << s2 << endl;

return 0;
}

2.2 友元类
TV 将Remote 类声明为友元类,Remote 对象成员函数可以
直接访问TV 类的私有部分

#include <iostream>
using namespace std;
class Remote;

struct TV {
public:
	enum {M_TV = 1, M_DVD};
	TV(int mode = M_TV) : m_mode(mode){}
private:
friend Remote;
int m_mode;
};

struct Remote {
	bool get_mode(TV const& that) {	
		cout << that.m_mode  << endl;
	}
};
int main (void) {
TV tv1(TV::M_TV);

Remote r1;
r1.get_mode(tv1);
return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值