本文介绍了未调用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!

推荐答案

打印不是虚函数,所以你是只依靠静态调度。这将根据对象的静态类型选择要调用的函数,在这种情况下为 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.

你应该打印虚拟:

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

然后,如果您使用C ++ 11,您可以标记 obj2 :: print as 覆盖为安全起见:

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

另请注意,您永远不会为<$​​ c $ c> newobj2

Also note that you never allocate any memory for newobj2.

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

07-24 04:31