覆盖私有功能,它与受保护功能有何不同?

Overriding a private function, how is it different from protected?

本文关键字:功能 受保护 何不同 覆盖      更新时间:2023-10-16

在下面的程序中,如果 GetPart(( 被保护而不是私有,那么这些类中的外部(派生(类或其他成员函数是否会有所不同? 即,是否存在编译错误,如果函数在基类中受到保护,则将其作为私有会导致编译错误?

我发现最近可以覆盖私有虚拟功能,这让我感到惊讶。从语义上讲,这似乎(对我来说(是受保护的工作,而不是私人的。

#include <iostream>
class A {
public:
A() {}
virtual ~A() {}
virtual void runFn() { GetPart(); }
private:
virtual void GetPart() = 0;
};
class B : public A {
public:
B() {}
virtual ~B() {}
private:
virtual void GetPart() override { std::cout << "GETPART RUN" << std::endl; }
};
int main()
{
B b;
b.runFn();
return 0;
}

请参阅 http://ideone.com/S9681V 以显示该行确实运行,因为函数被正确覆盖。

本主题造成很多混乱:即使允许子类覆盖虚拟私有成员函数,也不允许它们调用它们。

目前,这无法编译(演示 1(:

class B : public A {
public:
B() {}
virtual ~B() {}
private:
virtual void GetPart() override {
// This line would not compile
A::GetPart();
std::cout << "GETPART RUN" << std::endl;
}
};

保护GetPart()函数可以让上面的代码编译没有问题,但它需要你提供一个定义(演示 2(。

这是唯一的区别。