2014-06-21 94 views
0

假设我们有以下几点:从父级调用子静态函数?

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(); 

现在,如果我创建一个子类,它的运行功能将被外部调用,我怎么能重新定义foo的功能,同时还使用父运行功能,否则返回的东西吗?

编辑:对不起,让我添加一些更多的信息。假设虚拟函数run()是很多代码,所有这些都基本相同。父类和子类的唯一区别是我想要在矢量栏中指定哪些值,因此重新定义子类中的虚函数似乎有点浪费。但是,如果您重新定义Child :: bar并调用Child :: run(),则会使用Parent :: bar,因为它是在父类中定义的。有一些方法可以让行“vector Parent :: bar = Parent :: foo();”在Child类中知道使用“Child :: foo();”?

+0

我无法弄清楚你在问什么。你的意思是你想'Child :: foo()'返回'false'? –

+0

用更多的信息编辑了这个问题,希望它能帮到 – user2635787

+0

你能解释为什么'bar'需要是静态的吗?子类化覆盖静态值似乎有点奇怪。 – user1735003

回答

0

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

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

我已经在问题中添加了更多信息,希望这会有所帮助 – user2635787

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

+0

嗨,感谢您的回复。我用更多的信息编辑了问题 - 关键是我不想重写基本虚函数,因为它有很多代码,但调用run函数会导致使用基本虚函数。 – user2635787

+0

你是什么意思“调用运行函数,然后将导致基地foo被使用”? – 4pie0

+0

如果我调用Child :: run(),它会使用Parent :: foo()定义的Parent :: bar – user2635787

0

你真的不说你的问题太多,因此很难区分你需要解决潜在的XY问题。与你的架构

一个潜在的问题是,你有一个Parent份额一个静态变量bar但你似乎会以不同初始化它们ParentChildChild类。但是,只有一个bar由Parent和Child对象共享,与最后一次写入的对象无关。

那么,当同时使用ParentChild对象时,您会发现什么?你寻找的答案取决于你的答案。特别是,如果你的答案是'它的设计目的不是让ParentChild对象同时操作',那么这两个类绝对不应该共享一个静态变量。

相关问题