private,protected,public

来源:互联网 发布:js get和post的区别 编辑:程序博客网 时间:2024/06/03 18:21

private

  • 所有的data尽量用private属性

父类不能访问子类的private属性

有如下程序:

#include <iostream>#include <string>using namespace std;class Person{private:    string name;public:    void print();    Person(string aname):name("hello"){}};void Person::print() {    cout << "Person's name is " << name << endl;}class A {private:    int i;    Person man;public:    A():i(0),man("12"){cout << "A(), i = " << i << endl;}    ~A(){cout << "~A(), i = " << i << endl;}    void print();};void A::print() {    cout << "man's name is " << man.name << endl; //Error - 'name' is a private member of 'Person'}int main(){    A a;    a.print();    return 0;}

所以,即使一个对象包含了另一个对象,父对象也不能访问子对象的private属性。

protected

  • 只有parentchild可以访问
  • 一般用于设计一些只有parentchild可以访问的接口

public

  • 都可以访问
0 0
原创粉丝点击