简体   繁体   English

C ++重写函数未调用

[英]C++ overridden function not called

I am running into an issue where an overloaded function is not called, and the base function is called instead. 我遇到一个问题,其中没有调用重载函数,而是调用了基本函数。 I suspect this is related to how things are split between the project files. 我怀疑这与项目文件之间的拆分方式有关。

In files obj1.h/obj1.cpp I have something like this 在文件obj1.h / obj1.cpp中,我有这样的内容

class obj1{
public:
    void print();
};

void obj1::print(){
    cout << "obj1::print()";
}

In files obj2.h/obj2.cpp I have something like this: 在文件obj2.h / obj2.cpp中,我有类似以下内容:

#include "obj1.h"   
class obj2 : public obj1{
public:
    void print();
};

void obj2::print(){
    cout << "obj2::print()";
}

In separate files, I do something like this: 在单独的文件中,我执行以下操作:

#include "obj1.h"   
class obj3{    
public:
    vector<obj1*> objlist;
    void printobjs();
    void addobj(obj1* o);
};

void obj3::printobjs(){
    vector<obj1*>::iterator it;
    for (it=objList.begin(); it < objList.end(); it++)
        (*it)->print();

void obj3::addobj(obj1* o){
    objlist.push_back(o);
}

Then in a different file: 然后在另一个文件中:

#include "obj2.h"
obj3 o3;
main(){
    obj2* newobj2;
    newobj2 = new obj2();
    o3.addobj(newobj2);

    o3.printobjs();

My issue is that printobjs() results in the obj1.print() being called. 我的问题是printobjs()导致obj1.print()被调用。 (I have searched around a bit, and read a few dozen posts with overloading issues, but did not see a similar issue) (我进行了一些搜索,并阅读了几十篇有关超载问题的帖子,但没有看到类似的问题)

Can someone point me in the right direction on this? 有人可以为此指出正确的方向吗? Thanks! 谢谢!

print is not a virtual function, so you are just relying on static dispatch. print不是虚拟函数,因此您仅依赖静态调度。 This will select the function to call based on the static type of the object, which is obj1 in this case. 这将根据对象的静态类型(在这种情况下为obj1选择要调用的函数。

You should make print virtual: 您应该将print虚拟化:

class obj1{
public:
    virtual void print();
};

Then if you use C++11 you can mark obj2::print as override for safety's sake: 然后,如果您使用C ++ 11,为了安全起见,可以将obj2::print标记为override

class obj2 : public obj1{
public:
    void print() override;
};

Also note that you never allocate any memory for newobj2 . 还要注意,您永远不会为newobj2分配任何内存。

您应该将print()声明为虚拟的,以便为obj2对象调用obj2 :: print()。

virtual void print();

I am not entirely sure, it is log time since i did c++, but as I remember You should have the vectors contents be classes with pure virtual functions. 我不完全确定,自从我使用c ++以来已经是登录时间了,但是我记得您应该让vectors内容成为具有纯虚函数的类。

That should force it to look up the right method. 那应该迫使它查找正确的方法。

There is a stack overflow answer here, which is slightly related: 这里有一个堆栈溢出答案,该答案与以下内容略有相关:

Pure Virtual Class and Collections (vector?) 纯虚拟类和集合(向量?)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM