gpt4 book ai didi

C++抽象类继承虚函数

转载 作者:行者123 更新时间:2023-11-28 04:28:44 25 4
gpt4 key购买 nike

我有一个抽象基类,其中包含一些属性或成员元素以及一些公共(public)函数和一个公共(public)纯虚函数。在抽象类的派生类中,我想 (a) 将抽象基类的成员作为私有(private)成员访问,以及 (b) 公共(public)函数和定义的纯虚函数保持公共(public)状态。有办法吗?也就是说,AbstractBase 的 xxxx 和 derived 中的 yyyy 访问说明符应该是什么来实现这一点?

#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 保持为 protected 状态并将 yyyy 保持为公开状态,则 baseprivate1 将在 Derived 中受到保护并且不再是私有(private)的。或者,如果 xxxx 是公共(public)的/ protected 并且 yyyy 是私有(private)的,则 derived 中的函数变为私有(private)。

最佳答案

完成所需内容的一种方法是在派生类上使用 AbstractBase 的私有(private)继承。然后,您可以在 Derived 类的公共(public)访问说明符下使用 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;
}

关于C++抽象类继承虚函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53559850/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com