第二章 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指针表示指向当前类