未调用 C++ 覆盖的函数 [英] C++ overridden function not called

查看:32
本文介绍了未调用 C++ 覆盖的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个问题,即不调用重载函数,而是调用基函数.我怀疑这与项目文件之间的拆分方式有关.

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.

在文件 obj1.h/obj1.cpp 我有这样的东西

In files obj1.h/obj1.cpp I have something like this

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

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

在文件 obj2.h/obj2.cpp 我有这样的东西:

In files obj2.h/obj2.cpp I have something like this:

#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);
}

然后在不同的文件中:

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

    o3.printobjs();

我的问题是 printobjs() 导致 obj1.print() 被调用.(我搜索了一下,看了几十篇有超载问题的帖子,但没有看到类似的问题)

My issue is that printobjs() results in the obj1.print() being called. (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 不是虚函数,所以你只是依赖于静态调度.这将根据对象的静态类型选择要调用的函数,在本例中为 obj1.

print is not a virtual function, so you are just relying on static dispatch. This will select the function to call based on the static type of the object, which is obj1in this case.

你应该将 print 设为虚拟:

You should make print virtual:

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

那么,如果你使用 C++11,为了安全起见,你可以将 obj2::print 标记为 override:

Then if you use C++11 you can mark obj2::print as override for safety's sake:

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

还请注意,您永远不会为 newobj2 分配任何内存.

Also note that you never allocate any memory for newobj2.

这篇关于未调用 C++ 覆盖的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆