你能帮我解决这个问题吗?我有四个班。 蜜罐头:在C++中继承函数
class Honeypot
{
public:
int getNumberOfInterfaces();
Honeypot (int numberOfInterfaces);
virtual std::string typeHoneypot()=0;
protected:
int numberOfInterfaces;
};
Honeypot.cpp:
Honeypot::Honeypot(int numberOfInterfaces){
this-> numberOfInterfaces = numberOfInterfaces;
}
int Honeypot::getNumberOfInterfaces(){
return numberOfInterfaces;
}
类蜜罐有子HoneypotV和HoneypotN。现在,我创建的对象与neteorkInterfaces数:
Honeypot* NetworkType::createObject(int res1, int res2, int res3) {
if (res1 == 1 && res2 == 1 && res3 == 1) {
HoneypotV p1(3);
return &p1;
} else {
HoneypotN p2(3);
return &p2;
}
在主要功能:)
NetworkType select;
Honeypot *p;
p = select.createObject(1,1,1);
cout << p->typeHoneypot() << endl;
cout << p-> getNumberOfInterfaces() << endl;
typeHoneypot(是正确的,但getNumberOfInterfaces()返回的值-858993460,正确的是3
谢谢你的回复。
你访问一个未初始化的指针。您还返回了超出范围的变量的地址。第二,至少,有着名的[酒店房间响应](http://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope)。前者在[在这里]讨论(http://stackoverflow.com/questions/367633/what-are-all-the-common-undefined-behaviour-that-a-c-programmer-should-know-ab)。 – chris
您不应该返回对本地对象的引用。 http://stackoverflow.com/questions/4643713/c-returning-reference-to-local-variable – selalerer