如果我重写它,我可以调用基类的虚函数吗?
假设我有Foo
和Bar
这样的班级设置:
class Foo
{
public:
int x;
virtual void printStuff()
{
std::cout << x << std::endl;
}
};
class Bar : public Foo
{
public:
int y;
void printStuff()
{
// I would like to call Foo.printStuff() here...
std::cout << y << std::endl;
}
};
正如代码中所注释的那样,我希望能够调用我重写的基类的函数。 在Java中有super.funcname()
语法。 这在C ++中可能吗?
C ++语法如下所示:
class Bar : public Foo {
// ...
void printStuff() {
Foo::printStuff(); // calls base class' function
}
};
是,
class Bar : public Foo
{
...
void printStuff()
{
Foo::printStuff();
}
};
它与Java中的super
相同,只是它允许在有多重继承时从不同基地调用实现。
class Foo {
public:
virtual void foo() {
...
}
};
class Baz {
public:
virtual void foo() {
...
}
};
class Bar : public Foo, public Baz {
public:
virtual void foo() {
// Choose one, or even call both if you need to.
Foo::foo();
Baz::foo();
}
};
有时当你不在派生函数中时,你需要调用基类的实现......它仍然有效:
struct Base
{
virtual int Foo()
{
return -1;
}
};
struct Derived : public Base
{
virtual int Foo()
{
return -2;
}
};
int main(int argc, char* argv[])
{
Base *x = new Derived;
ASSERT(-2 == x->Foo());
//syntax is trippy but it works
ASSERT(-1 == x->Base::Foo());
return 0;
}
链接地址: http://www.djcxy.com/p/54151.html
上一篇: Can I call a base class's virtual function if I'm overriding it?