c++类中的私有成员和受保护成员有什么区别?

我从最佳实践惯例中了解到,没有在类外部调用的变量和函数应该是私有的,但看看我的MFC项目,MFC似乎更倾向于受保护。

有什么区别,我应该用哪个?


当前回答

受保护的成员只能由类的后代和同一模块中的代码访问。私有成员只能被声明它们的类以及同一模块中的代码访问。

当然,朋友函数把这个扔出窗外,但是。

其他回答

Private: It is an access specifier. By default the instance (member) variables or the methods of a class in c++/java are private. During inheritance, the code and the data are always inherited but is not accessible outside the class. We can declare our data members as private so that no one can make direct changes to our member variables and we can provide public getters and setters in order to change our private members. And this concept is always applied in the business rule. Protected: It is also an access specifier. In C++, the protected members are accessible within the class and to the inherited class but not outside the class. In Java, the protected members are accessible within the class, to the inherited class as well as to all the classes within the same package.

私有成员只能从类内部访问,受保护成员可以在类和派生类中访问。这是面向对象语言中继承的一个特性。

在c++中可以有私有、受保护和公共继承,这将决定哪些派生类可以在继承层次结构中访问。例如,c#只有公共继承。

这完全取决于您想要做什么,以及您希望派生类能够看到什么。

class A
{
private:
    int _privInt = 0;
    int privFunc(){return 0;}
    virtual int privVirtFunc(){return 0;}
protected:
    int _protInt = 0;
    int protFunc(){return 0;}
public:
    int _publInt = 0;
    int publFunc()
    {
         return privVirtFunc();
    }
};

class B : public A
{
private:
    virtual int privVirtFunc(){return 1;}
public:
    void func()
    {
        _privInt = 1; // wont work
        _protInt = 1; // will work
        _publInt = 1; // will work
        privFunc(); // wont work
        privVirtFunc(); // will work, simply calls the derived version.
        protFunc(); // will work
        publFunc(); // will return 1 since it's overridden in this class
    }
}

Private =只能由母类(基类)访问 (只有我父母才能进我父母的卧室)

Protected =母类(基类)和她的子类可以访问 (只有父母可以进父母的卧室,但允许儿子/女儿进父母的卧室)

Public =母类(基类)、子类和其他所有人都可以访问 (只有我父母才能进我父母的卧室,但那是家庭聚会——我的家是我的家)

Private:可由类成员函数和好友函数或好友类访问。 对于c++类,这是默认的访问说明符。

Protected:可由类成员函数、友元函数或友元类及派生类访问。

您可以根据需要将类成员变量或函数(甚至是typedefs或内部类)保留为私有或受保护。 大多数情况下,保持类成员为私有,并添加get/set函数进行封装。这有助于代码的维护。 一般来说,当你想要保持公共函数模块化或消除重复代码而不是将整个代码写入单个函数时,就会使用私有函数。这有助于代码的维护。

更多细节请参考这个链接。