gpt4 book ai didi

c++ - 从父调用子静态函数?

转载 作者:行者123 更新时间:2023-11-28 06:49:10 27 4
gpt4 key购买 nike

假设我们有以下内容:

class Parent {
public:
virtual void run() {
for (int i = 0 ; i < bar.size() ; ++it)
cout << i << "\n" ;
};
protected:
static vector<int> foo() {return vector r({1,2,3,4,5});};
static vector<int> bar;
}
vector<int> Parent::bar = Parent::foo();

现在,如果我创建一个子类,其 run 函数将被外部调用,我如何重新定义 foo 函数以返回其他内容,同时仍然使用父 run 函数?

编辑:抱歉让我添加更多信息。假设虚函数run()是一大堆代码,所有这些代码本质上都是一样的。父类和子类的唯一区别是我想在vector bar中指定什么值,所以在子类中重新定义虚函数似乎有点浪费。但是,如果您重新定义 Child::bar 并调用 Child::run(),则会使用 Parent::bar,因为它是在父类中定义的。有什么方法可以让“vector Parent::bar = Parent::foo();”这一行知道在 Child 类中使用“Child::foo();”吗?

最佳答案

像往常一样。覆盖派生类中的基虚函数。

class Parent {
public:
virtual bool run() {return bar;};
static bool foo() {return true;};
static bool bar;
};

class Child: public Parent
{
public:
static bool foo() { return false;};
};

然后您仍然可以使用应用 Base:: 范围解析的基础版本:

int main() {

bool bc = Child::foo();
bool bp = Parent::foo();

std::cout << bc << bp;
return 0;
}

http://ideone.com/TdaNQ5

关于c++ - 从父调用子静态函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24339727/

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