C++this指针、友元等小属性集锦

this指针

关键字this包含“当前对象的地址”,即this指针的值为&object

在 某个类的成员方法 调用 其他成员方法 时,编译器将隐式得传递this指针。

* 调用静态方法时,不会隐式得传递this指针(静态方法是所有实例共享的)。

* 要在静态方法里 使用非静态实例变量,应显示地声明一个形参,并将实参设置为this指针。

class A{
private:
	int age;
	void fun(string test){
		cout << test;
	}
public:
	void use(){
		fun("play this");
		//等价于fun(this, "play this");
	}

	void set(int num){
		this->age = num;
		//等价于age = num;
	}
};

 

友元

友元类和友元函数,可以从外部访问 类的私有数据成员和方法。友元类里的所有方法都能访问Human类的私有数据成员和方法。

#include <iostream>
#include <string>
using namespace std;

class Human{
private:
	friend void DisplayAge(const Human& person);   //声明友元函数
	string name;
	int age;
public:
	Human(string humansName, int humansAge){
		name = humansName;
		age = humansAge;
	}
};

void DisplayAge(const Human& person){   //定义友元函数
	cout << person.age << endl;   //友元函数访问类的私有成员
}

int main(){
	Human firstMan("Adam", 25);
	cout << "Accessing private member age via friend function: ";
	DisplayAge(firstMan);
	return 0;
}
#include <iostream>
#include <string>
using namespace std;

class Human{
private:
	friend class Utility;   //声明友元类
	string name;
	int age;
public:
	Human(string humansName, int humansAge){
		name = humansName;
		age = humansAge;
	}
};

class Utility{   //定义友元类
public:
	static void DisplayAge(const Human& person){
		cout << person.age << endl;   //友元类里使用类的私有成员属性
	}
};

int main()
{
	Human firstMan("Adam", 25);
	cout << "Accessing private member age via friend class: ";
	Utility::DisplayAge(firstMan);
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值