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

标签 c++ inheritance

假设我们有以下内容:

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/

相关文章:

c++ - 使用堆或堆栈变量更好吗?

c++ - 在 matlab 中调用时无法在 C++ 中使用 opencv 读取图像

go - 了解golang中的继承与组合

c++ 类继承,未定义对 'Class::Constructor()' 的引用

Java:从父类(super class)变量调用子类方法

c++ - 在 C++ 中使用关键字 using 声明模板化函数指针的语法

c++ - 为什么 __builtin_popcount 比我自己的位计数函数慢?

c++ - 在 C++ 中将两个字符串组合成一个变量

c++ - 将派生类传递给基类参数的函数

C++ 析构函数泄漏动态内存