Ale*_*lex 315 c++ overriding virtual-functions
假设我有课程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;
}
};
Run Code Online (Sandbox Code Playgroud)
正如在代码中注释的那样,我希望能够调用我所覆盖的基类函数.在Java中有super.funcname()语法.这在C++中是否可行?
sth*_*sth 417
C++语法是这样的:
class Bar : public Foo {
// ...
void printStuff() {
Foo::printStuff(); // calls base class' function
}
};
Run Code Online (Sandbox Code Playgroud)
Ale*_*x B 114
是,
class Bar : public Foo
{
...
void printStuff()
{
Foo::printStuff();
}
};
Run Code Online (Sandbox Code Playgroud)
它与superJava中的相同,只是它允许在具有多个继承时从不同的基础调用实现.
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();
}
};
Run Code Online (Sandbox Code Playgroud)
Alw*_*ing 66
有时你需要调用基类的实现,当你不在派生函数中时...它仍然有效:
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;
}
Run Code Online (Sandbox Code Playgroud)
Mar*_*ner 27
为了防止你为你班上的很多功能做到这一点:
class Foo {
public:
virtual void f1() {
// ...
}
virtual void f2() {
// ...
}
//...
};
class Bar : public Foo {
private:
typedef Foo super;
public:
void f1() {
super::f1();
}
};
Run Code Online (Sandbox Code Playgroud)
如果要重命名Foo,这可能会节省一些写入.
如果要从派生类中调用基类函数,只需在提取基类名称(如Foo :: printStuff())时调用重写函数.
代码在这里
#include <iostream>
using namespace std;
class Foo
{
public:
int x;
virtual void printStuff()
{
cout<<"Base Foo printStuff called"<<endl;
}
};
class Bar : public Foo
{
public:
int y;
void printStuff()
{
cout<<"derived Bar printStuff called"<<endl;
Foo::printStuff();/////also called the base class method
}
};
int main()
{
Bar *b=new Bar;
b->printStuff();
}
Run Code Online (Sandbox Code Playgroud)
同样,您可以在运行时确定使用该类的对象(派生或基础)调用哪个函数.但这要求您在基类中的函数必须标记为虚拟.
代码如下
#include <iostream>
using namespace std;
class Foo
{
public:
int x;
virtual void printStuff()
{
cout<<"Base Foo printStuff called"<<endl;
}
};
class Bar : public Foo
{
public:
int y;
void printStuff()
{
cout<<"derived Bar printStuff called"<<endl;
}
};
int main()
{
Foo *foo=new Foo;
foo->printStuff();/////this call the base function
foo=new Bar;
foo->printStuff();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
221925 次 |
| 最近记录: |