C++ 面向对象:属性和行为、访问权限、与struct区别

面向对象的三大特性:封装、继承和多态

封装的语法,可见以下:

class 类名{

    访问权限

           属性~成员变量

           行为~成员函数

};

具体见以下代码示例:

#include
using namespace std;

class People{
public:
    int high;
    int weight;

    void eat(int food1) {
        weight += food1;
    }

    void noeat(int food1) {
        weight -= food1;
    }
};

int main() {
    People lurenjia;
    lurenjia.weight = 120;
    lurenjia.high = 160;
    lurenjia.eat(20);
    cout << lurenjia.weight;
    return 0;
}

访问权限:public-类内类外都可以访问。protected-类内可以访问,类外不可以访问,子类可以访问。pridate-类内可以访问,类外不可以访问,子类不可以访问。

#include
using namespace std;

class People{
public:
    int msg1;
protected:
    int msg2;
private:
    int msg3;
    void getmsg() {
        msg1 = 1;
        msg2 = 2;
        msg3 = 3;
    }
};
class People1 : public People {
    void getmsg() {
        msg1 = 2;
        msg2 = 3;
    }
};

int main() {
    People msg;
    msg.msg1;
    return 0;
}

class和struct的区别,他们两者都可以定义对应的成员函数:

struct的话,他的权限默认是公共的。

class的话,他的权限默认是私有的。

可见以下代码:

#include
using namespace std;

class a {
   int msg1;
   void function() {
       msg1 = 6;
   }
};
struct b {
    int msg2;
    void function() {
        msg2 = 5;
    }
};
int main() {
    a a1;
    b b1;
    b1.msg2;
    return 0;
}

你可能感兴趣的:(c++,开发语言,算法)