C++ overridden function not called(未调用 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++ 覆盖的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:未调用 C++ 覆盖的函数
基础教程推荐
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 初始化列表*参数*评估顺序 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- CString 到 char* 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
