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 obj1
in 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++ 覆盖的函数
基础教程推荐
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- 设计字符串本地化的最佳方法 2022-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- C++,'if' 表达式中的变量声明 2021-01-01