c++类中的私有成员和受保护成员有什么区别?
我从最佳实践惯例中了解到,没有在类外部调用的变量和函数应该是私有的,但看看我的MFC项目,MFC似乎更倾向于受保护。
有什么区别,我应该用哪个?
c++类中的私有成员和受保护成员有什么区别?
我从最佳实践惯例中了解到,没有在类外部调用的变量和函数应该是私有的,但看看我的MFC项目,MFC似乎更倾向于受保护。
有什么区别,我应该用哪个?
当前回答
与私有属性和方法不同,标记为受保护的属性和方法在子类中仍然可见。
除非您不想在可能的子类中使用或提供重写该方法的可能性,否则我会将它们设为private。
其他回答
这完全取决于您想要做什么,以及您希望派生类能够看到什么。
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
}
}
a类的公共成员对所有人都是开放的。
类a的受保护成员不能在a的代码之外访问,但可以从派生自a的任何类的代码访问。
类a的私有成员不能在a的代码之外或从a派生的任何类的代码中访问。
因此,最终,在受保护还是私有之间做出选择是为了回答以下问题:您愿意对派生类的程序员给予多少信任?
默认情况下,假定派生类不可信,并将成员设为private。如果你有一个很好的理由让它的派生类可以自由访问母类的内部内容,那么你可以让它们受到保护。
由于不需要公共成员函数来获取和更新派生类中的受保护成员,这提高了代码的效率,并减少了需要编写的代码量。然而,派生类的程序员应该知道他在做什么。
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.
受保护的非静态基类成员可以被派生自该基类的任何类的成员和友元访问,方法是使用以下方法之一:
指向直接或间接派生类的指针 对直接或间接派生类的引用 直接或间接派生类的对象