C++(五):友元函数&运算符重载

#include <stdio.h>
#include <stdlib.h>
#include <iostream>


using namespace std;
//友元函数
class A{
public:
	A(int i) {
		this->i = i;
	}
	void myprint() {
		cout << i << endl;
	}
	//友元函数
	friend void modify_i(A* p, int a);
private:
	int i;
};

//友元函数的实现,在友元函数中可以访问私有的属性
void modify_i(A* p,int a) {
	p->i = a;
}
void main() {
	A* a = new A(10);
	a->myprint();//10
	modify_i(a,22);
	a->myprint();//22

	getchar();
}
/**************************************************************/

//友元类

class A {

	//友元类
	friend class B;
public:
	A() {

	}
	A(int i) {
		this->i = i;
	}
	void myprint() {
		cout << i << endl;
	}
	
private:
	int i;
};

class B
{
public:
	B(){

	}
	//B这个友元类可以访问A类的任何成员
	void accessAny() {
		a.i = 50;
		a.myprint();
	}
private:
	A a;
};

void main() {
	A* a = new A(10);
	a->myprint();
	B* b = new B();
	b->accessAny();
	getchar();
}
/**************************************************************/

//运算符重载

class Point
{
public:
	Point(int x = 0, int y = 0) {
		this->x = x;
		this->y = y;
	}
	void myprint() {
		cout << x <<","<< y << endl;
	}
public:
	int x;
	int y;
};

//重载+号运算符
Point operator+(Point &p1,Point &p2) {
	Point tmp(p1.x+p2.x,p1.y+p2.y);
	return tmp;
}
//重载-号运算符
Point operator-(Point &p1, Point &p2) {
	Point tmp(p1.x - p2.x, p1.y - p2.y);
	return tmp;
}
void main() {
	Point p1(10,10);
	Point p2(10, 10);

	Point p3 = p1 + p2;
	p3.myprint();

	getchar();
}
/**************************************************************/
//成员函数,运算符重载

class Point
{
public:
	Point(int x = 0, int y = 0) {
		this->x = x;
		this->y = y;
	}
	//成员函数,运算符重载
	Point operator+(Point &p2) {
		Point tmp(this->x + p2.x, this->y + p2.y);
		return tmp;
	}
	void myprint() {
		cout << x << "," << y << endl;
	}
public:
	int x;
	int y;
};

void main() {
	Point p1(10, 10);
	Point p2(10, 10);

	//运算符重载,本质还是函数调用
	Point p3 = p1 + p2;
	p3.myprint();

	getchar();
}
/**************************************************************/

//当属性私有时,通过友元函数完成运算符重载

class Point{
	friend Point operator+(Point &p1, Point &p2);

public:
	Point(int x = 0, int y = 0) {
		this->x = x;
		this->y = y;
	}

	void myprint() {
		cout << x << "," << y << endl;
	}
private:
	int x;
	int y;
};
//重载+号运算符
Point operator+(Point &p1, Point &p2) {
	Point tmp(p1.x + p2.x, p1.y + p2.y);
	return tmp;
}
void main() {
	Point p1(10, 10);
	Point p2(10, 10);

	//运算符重载,本质还是函数调用
	Point p3 = p1 + p2;
	p3.myprint();

	getchar();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值