C++访问修饰符

Note:

1、class定义时,前面不能有修饰符。(如果是在.NET平台上开发的话,可以设置/clr编译选项)

2、class中的成员默认是private的,而struct和union中的成员默认是public的。(C#中class和struct里面的所有成员默认都是private)

3、子类是class,父类默认是private继承; 子类是struct,父类默认是public继承; 而Unions不能继承其他的对象。如下:

 class BaseClass
 {
 public:
  int age;
 protected:
  int sex;
 };

 class MyClass1 : BaseClass // 默认是private
  
 };

 struct MyStruct: BaseClass // 默认是public
 
 };

 

 -----------------------------------------------------------------

public:

1、修饰class里的成员,这些成员可以在class的内部被访问,也可以在外部被访问。

2、公有成员可以被继承。

3、当一个class作为父类被继承时,可以用public来修饰。如下:

class Child : public Father
  };

此时,父类中的public和protected成员都可以被子类继承,并且修饰符与父类一样。

 

protected:

1、修饰class里的成员,这些成员可以在class的内部被访问,也可以被友元类和友元方法访问,不可以在外部被访问。

2、保护型成员可以被继承。

3、当一个class作为父类被继承时,可以用protected来修饰。如下:

class Child : protected Father
  };

此时,父类中的public和protected成员都可以被子类继承,并且修饰符都是protected。


private:

1、修饰class里的成员,这些成员只可以在class的内部被访问。

2、私有成员可以被继承,但不能被子类访问。

3、当一个class作为父类被继承时,可以用private来修饰。如下:

class Child : private Father
  };

此时,父类中的public和protected成员都可以被子类继承,并且修饰符都是private。

 

疑点(错误无处不在)

1、当父类被私有继承的时候,只影响非静态变量的访问修饰符,静态变量不受影响。子类可以访问父类公有和保护型的静态变量。

如下面例子:

class Base
{
public:
    int Print();             // Nonstatic member.
    static int CountOf();    // Static member.
protected:
    static int Max(); // Static member.
};

// Derived1 declares Base as a private base class.
class Derived1 : private Base
{
};
// Derived2 declares Derived1 as a public base class.
class Derived2 : public Derived1
{
    int ShowCount();    // Nonstatic member.
};
// Define ShowCount function for Derived2.
int Derived2::ShowCount()
{
   // Call static member function CountOf explicitly.
    int cCount = Base::CountOf();     // OK.
    cCount = Base::Max();     // OK.
   // Call static member function CountOf using pointer.
    cCount = this->CountOf();  // C2247. Conversion of
                               //  Derived2 * to Base * not
                               //  permitted.
    return cCount;
}

事实上,int cCount = Base::CountOf(); // OK. 这句话编译出错

2、Protected members that are also declared as static are accessible to any friend or member function of a derived class. Protected members that are not declared as static are accessible to friends and member functions in a derived class only through a pointer to, reference to, or object of the derived class.

有待考证。

3、Files compiled with /LN are not affected by this behavior. In this case, all managed classes (either public or private) will be visible.

有待考证。

原文地址:https://www.cnblogs.com/wwb0111/p/3098966.html