第二章 C++编程之类的私有数据

第二章 C++编程之类的私有数据

c++的类中的私有数据不能被外部直接访问,只能通过类中的共有方法去设置

2.1 类的私有数据

//以person类为例:包含私有类的数据常量:名字、年龄
//通过public的类方法设置类对象的私有数据
#include<stdio.h>
class Person{//注意类的
private:
	char *name;
	int age;
public:
	void setName(char*n)
	{
		name = n;
	}
	void setAge(int a)
	{
		age = a;
	}
	void printInfo(void){
		printf("name is %s,age is %d\n",name,age);
	}
};
int main(int argc ,char**argv)
{
	Person person;
	//person.age = 10;//此处编译报错:私有数据不能访问
	person.setName("Peter");
	person.setAge(19);
	person.printInfo();
	return 0;
}

2.1 引入类中的this指针

//以person类为例:包含私有类的数据常量:名字、年龄
//通过public的类方法设置类对象的私有数据
#include<stdio.h>
class Person{//注意类的
private:
	char *name;
	int age;
public:
	void setName(char*name)
	{
		this->name = name;//区别在这里
	}
	void setAge(int age)
	{
		this->age = age;//区别在这里
	}
	void printInfo(void){
		printf("name is %s,age is %d\n",name,age);
	}
};
int main(int argc ,char**argv)
{
	Person person;
	//person.age = 10;//此处编译报错:私有数据不能访问
	person.setName("2Peter");
	person.setAge(19);
	person.printInfo();
	return 0;
}

2.2 类中的私有数据和this指针总结

1、类中私有数据不能直接访问
2、this指针表示指向当前类

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值