【发布时间】:2023-03-14 06:06:01
【问题描述】:
我有一个抽象基类,其中包含一些属性或成员元素以及一些公共函数和一个公共纯虚函数。在抽象类的派生类中,我想(a)访问抽象基类的成员作为私有成员,(b)公共函数和定义的纯虚函数保持公共。有没有办法做到这一点?也就是说,要实现这一点,派生的 AbstractBase 和 yyyy 访问说明符的 xxxx 应该是什么?
#include <iostream>
class AbstractBase {
xxxx: <-- // protected/private/public?
std::string baseprivate1;
public:
virtual void set_privates() = 0;
void print() { std::cout << baseprivate1 << std::endl; }
void foo() { // some definition here }
};
class Derived : yyyy AbstractBase { <--- //public/protected/private?
private:
std::string derivedprivate1;
public:
void set_privates() {
// I want this baseprivate1 to be private in derived class as well.
// When I choose xxxx as protected and yyyy as public, the baseprivate1 is protected.
this->baseprivate1 = "Base private1";
this->derivedprivate1 = "Derived private1";
}
void print() {
AbstractBase::print();
std::cout << this->derivedprivate1;
}
// When I choose xxxx as protected and yyyy as protected
// foo becomes protected and unable to call from outside
// I want the foo of abstract base to be public here as well.
};
int main(int argc, char *argv[]){
Derived d;
d.set_privates();
d.print();
d.foo(); // I should be able to call foo of abstract base class
}
它可能会被混淆为Difference between private, public, and protected inheritance 的重复。如果您将 xxxx 保持为受保护而 yyyy 保持为公共,则 baseprivate1 将在 Derived 中受到保护并且不再是私有的。或者,如果 xxxx 是 public/protected 并且 yyyy 是私有的,则派生的函数将变为私有。
【问题讨论】:
-
简答:xxxx - 受保护,yyyy - 公共
-
@slava 使 baseprivate1 在派生而不是私有中受到保护。
-
@RamakrishnanKannan 您的数据应提供尽可能低的访问权限,在这种情况下,
protected是必要的,无论您是否想要。 -
你想要的建议了一个可能没有充分考虑的班级策略。我怀疑是XY problem。