你能幫我解決這個問題嗎?我有四個班。 蜜罐頭:在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