我刚刚注意到一些奇怪的事情,当我在类中添加“虚拟关键字”(除构造函数之外的任何函数)时,我无法在 GDB 中显示对象的内容。 GDB 说“不完整类型”
这是代码:
////////////////reco.h //////////////
#ifndef RECO_H
#define RECO_H
#include <iostream>
#include <string>
class reco {
public:
reco(float weight);
~reco(void);
float getWeight();
private:
float weight;
};
#endif
/////////////////reco.cpp //////////////
#include <iostream>
#include <string>
#include "reco.h"
using namespace std;
reco::reco(float weight) {
weight = weight;
}
reco::~reco(void) {
cout << "destructor reco" << endl;
}
float reco::getWeight() {
return weight;
}
////////////// main.cpp //////////////
#include <iostream>
#include <string>
#include "reco.h"
using namespace std;
int main() {
reco* s = new reco(5.0);
cout << s->getWeight() << endl;
delete s;
return 0;
}
然后使用GDB:
gdb main.exe
breakpoint main.cpp:11 <---- (cout)
run
print *s
$1 = { weight = 5 }
然后,如果我将其中一个函数设为“虚拟”,然后我重新尝试打印我的*s
GDB 的指针,它说:
“不完整类型”
看起来 VTABLE 发生了一些事情,就好像“virtual”关键字隐藏了我的 Reco 类的实现。我知道编译器会进行后期绑定,然后 VTABLE 查找是在运行时完成的,但是当 GDB 调试它时程序已经在运行,对吗?
将“set print vtbl”设置为“on”。
如果我使用ptype s
,我得到<incomplete type>
再次留言。
如果我检查地址x/540f80
,它说“无法访问内存”
我不知道为什么仅仅添加这个关键字就会使我的对象的类型不完整?
非常感谢你的帮助 !
我注意到的最后一件事:
虚拟:
reco.cpp -> g0 and main.cpp -> g = incomplete type
reco.cpp -> g and main.cpp ->g = ok
没有虚拟
reco.cpp -> g0 and main.cpp -> g = ok
reco.cpp -> g and main.cpp ->g = ok