假设我有这样的类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++中可行吗?
如果你想从基类的派生类中调用基类的函数,你可以在被重写的函数内部调用,并提到基类名(如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();
}
同样,您可以在运行时使用该类的对象(派生类或基类)确定调用哪个函数。但这要求基类中的函数必须标记为虚函数。
下面的代码
#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();
}
如果你想从基类的派生类中调用基类的函数,你可以在被重写的函数内部调用,并提到基类名(如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();
}
同样,您可以在运行时使用该类的对象(派生类或基类)确定调用哪个函数。但这要求基类中的函数必须标记为虚函数。
下面的代码
#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();
}