2013-05-27 115 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

你返回一个指针到本地变量,但是当你从你的函数退出,所有局部变量将被销毁,指针将参考已销毁的对象

关于在主函数代码:你声明一个指向对象并且还没有初始化,所以指针指向一些垃圾在内存