【问题标题】:call child static function from parent?从父级调用子静态函数?
【发布时间】:2014-06-21 08:19:27
【问题描述】:

假设我们有以下内容:

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()是很多代码,所有的代码本质上都是一样的。父类和子类的唯一区别是我要在向量栏中指定什么值,所以在子类中重新定义虚函数似乎有点浪费。但是,如果您重新定义 Child::bar,并调用 Child::run(),则会使用 Parent::bar,因为它是在父类中定义的。有没有办法让“vector Parent::bar = Parent::foo();”这一行知道在 Child 类中使用“Child::foo();”吗?

【问题讨论】:

  • 我不知道你在问什么。你的意思是你想让Child::foo()返回false
  • 用更多信息编辑了这个问题,希望它会有所帮助
  • 您能解释一下为什么bar 需要是静态的吗?覆盖静态值的子类化似乎有点奇怪。
  • 我并没有严格地为 bar 变量进行子类化,还有许多其他继承的东西我没有包括在这个例子中。我想我不需要将其设为静态,然后我可以将其设为虚拟,尽管它对于任何实例都是相同的值。

标签: c++ inheritance


【解决方案1】:

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

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

【讨论】:

  • 您好,感谢您的回复。我已经用更多信息编辑了问题 - 关键是我不想重写基本虚函数,因为它有很多代码,但是调用 run 函数会导致使用基本 foo。
  • “调用 run 函数会导致使用基础 foo”是什么意思?
  • 如果我调用 Child::run(),它将使用 Parent::bar,它由 Parent::foo() 定义
【解决方案2】:

我不确定你到底想要什么。但是,您可以像这样覆盖静态函数,

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

【讨论】:

  • 我在问题中添加了更多信息,希望对您有所帮助
【解决方案3】:

你真的没有对你的问题说太多,因此很难区分你需要什么和潜在的 XY 问题。

您的体系结构的一个潜在问题是您有一个 Parent 和一个 Child 类,它们共享一个静态变量 bar 但您似乎为 ParentChild 类。但是,只有一个 bar 由 Parent 和 Child 对象共享,与最后写入它的人无关。

那么,当ParentChild 对象同时使用时,您会期待什么?您寻找的答案取决于您对此的答案。特别是,如果您的答案是“它并非旨在让 ParentChild 对象同时运行”,那么这两个类绝对不应共享静态变量。

【讨论】:

    猜你喜欢
    • 2011-10-04
    • 2022-01-13
    • 2011-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多