C++之友元函数与友元类使用

1.友元类

#include <iostream>
using namespace std;

class Date {
public:
	Date(int year) {
		this->year = year;
	}
	friend class Test; //声明外界可以访问Data.year的友元类Test

private:
	int year;
};

class Test {
public:
	static void show() {
		Date birthday(2022);
		cout <<"before: " << birthday.year << endl;
		birthday.year = 2000;
		cout <<"after: "<< birthday.year << endl;
	}
};

int main(){
  Test::show();
	return 0;
}

2.友元函数

#include <iostream>
using namespace std;

class Date {
public:
	Date (int year) {
		this->year = year;
	}
	friend void test();//声明外界可以访问Data.year的友元函数test()
	
private:
	int year;
};

void test() {
	Date birthday(2020);
	cout <<"before: " << birthday.year << endl;
	birthday.year = 2000;
	cout <<"after: "<< birthday.year << endl;
}

int main(){
	test();
	return 0;
}

猜你喜欢

转载自blog.csdn.net/u010164190/article/details/126345318