[英]How do I call an overloaded function from a function in the base class?
I have a class (B) that inherits another class (A). 我有一个继承另一个类(A)的类(B)。 I want to call a function from class A that has been overridden.
我想调用已被覆盖的A类函数。 I also want to be able to call the overridden function independent of what class inherited the base (say
class C : public A
, where I want to call C's version of the function.) 我还希望能够独立于继承基类的类调用重写函数(比如
class C : public A
,我想调用C函数的版本。)
Here's an example 这是一个例子
class A {
public:
void callF();
virtual void f() {};
};
class B : public A {
public:
void f();
};
void A::callF()
{
//FYI, I want to be able to call this without knowing what the super class is.
f();
}
void B::f()
{
std::cout << "I want this function to be called, but instead the default f() is called.";
}
Edit: In my real code, I have an std::vector<A> aVector;
编辑:在我的真实代码中,我有一个
std::vector<A> aVector;
. 。 Then I would call
aVector.push_back(B());
然后我会调用
aVector.push_back(B());
. 。 If I called
aVector[0].callF();
如果我调用
aVector[0].callF();
, The default a::f()
would be called. ,将调用默认的
a::f()
。 As answered below, I have a problem with slicing. 如下所述,我有切片问题。
Your construction: 你的建设:
vector_of_A.push_back( B() );
doesn't store a B
in the vector. 不会在矢量中存储
B
It constructs a B
, then constructs an A
from that, then stores that A
in the vector. 它构造一个
B
,然后构造一个A
从这一点,那么,其存储A
在载体中。 As a consequence, you experience slicing. 因此,您将体验切片。
See this for more info: 有关详细信息,请参阅此
https://stackoverflow.com/a/4403759/8747 https://stackoverflow.com/a/4403759/8747
Your code is correct. 你的代码是正确的。
You may be getting the behavior you observed because your were calling f() or callF() from the constructor of A. That's the only case I can think of where A::f() would get invoked instead of B::f(). 您可能正在获得您观察到的行为,因为您正在从A的构造函数中调用f()或callF()。这是我能想到的唯一一种情况,我可以想到A :: f()将被调用而不是B :: f( )。
Your code works for me with this little test program: 您的代码适用于我这个小测试程序:
int main()
{
// Instantiate B, and reference it via a base class pointer.
A* b = new B;
b->callF();
delete b;
}
Output: 输出:
I want this function to be called, but instead the default f() is called.
When calling a virtual member function within a base class member function, it's the derived member function that will be invoked. 在基类成员函数中调用虚拟成员函数时,它是将被调用的派生成员函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.