02_类的控制访问

来源:互联网 发布:window10 stc isp软件 编辑:程序博客网 时间:2024/06/05 06:15

类的控制访问

一、c结构体和c++类中的成员名称

在c结构体中的成员称为变量,在c++类中变量被称为 数据成员,类中的函数被称为 成员函数。在c++中类的首字母应该大小。

二、c++中类的访问权限

在c++类中默认权限为private,private只供类内部使用,public类外的程序可以使用。

三、c++类的封装

class Person{    private:        char *name;        int age;        char *work;    public:        void setName(char *name)        {            this->name = name;        }        void setAge(int age)        {            if(age < 0 || age > 150)            {                this->age = 0;                return -1;            }            this->age = age;            return 0;        }        void printInfo(void)        {            printf("name = %s, age = %d, work = %s\n", name, age, work);         }    };

1、为什么要封装?

为了防止用户对数据成员进行错误的设置,比如设置年龄不可能为负数,故要进行封装。

2、this指针

this指针表示指向当前对象

3、“this->name = name;”中的name是指类中的数据成员name,还是要设置的name?

要设置的name,就近原则。