2013-05-27 114 views
0

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

謝謝你的回覆。

+7

你訪問一個未初始化的指針。您還返回了超出範圍的變量的地址。第二,至少,有着名的[酒店房間響應](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

+1

您不應該返回對本地對象的引用。 http://stackoverflow.com/questions/4643713/c-returning-reference-to-local-variable – selalerer

回答

1

如果你想回到它應該dynamiclly實例化對象:

Honeypot* NetworkType::createObject(int res1, int res2, int res3) { 
    if (res1 == 1 && res2 == 1 && res3 == 1) { 
    HoneypotV *p1 = new HoneypotV(3); 
    return p1; 
} else { 
    HoneypotN *p2 = new HoneypotN(3); 
    return p2; 
} 
+0

謝謝你的幫助! – Mato

3

你返回一個指針到本地變量,但是當你從你的函數退出,所有局部變量將被銷燬,指針將參考已銷燬的對象

關於在主函數代碼:你聲明一個指向對象並且還沒有初始化,所以指針指向一些垃圾在內存