C++抽象类继承虚拟函数



我有一个抽象基类,带有一些属性或成员元素、一些公共函数和一个公共纯虚拟函数。在抽象类的派生类中,我想(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
}

它可以被混淆为私有继承、公共继承和受保护继承之间的差异的重复。如果将xxxx保持为受保护状态,将yyyy保持为公共状态,那么baseprivate1将在Derived中受到保护,不再是私有的。或者,如果xxxx是公共/受保护的,而yyyy是私有的,则派生函数将变为私有函数。

实现您想要的功能的一种方法是在派生类上使用AbstractBase的私有继承。然后,您可以在派生类的公共访问说明符下使用using声明来公开AbstractBase的一些方法。

#include <iostream>
class AbstractBase {
public:
std::string baseprivate1;
virtual void set_privates() = 0;
void print() { std::cout << baseprivate1 << std::endl; }
void foo() { /* some definition here */ }
};
class Derived : private AbstractBase { // use private inheritance on AbstractBase
private:
std::string derivedprivate1;
public:
// expose AbstractBase's methods with using-declarations
using AbstractBase::foo;
using AbstractBase::print;
void set_privates() {
this->baseprivate1 = "Base private1";
this->derivedprivate1 = "Derived private1";
}
void print() {
AbstractBase::print();
std::cout << this->derivedprivate1 << std::endl;;
}
};
int main(int argc, char *argv[]){
Derived d;
d.set_privates();
d.print();
d.foo();
return 0;
}

相关内容

最新更新