简体   繁体   English

C ++中函数的继承

[英]Inheritance of functions in C++

Can you help me please with this problem? 您能帮我解决这个问题吗? I have four classes. 我有四节课。 Honeypot header: 蜜罐头:

class Honeypot
{

public:
int getNumberOfInterfaces();
Honeypot (int numberOfInterfaces);
virtual std::string typeHoneypot()=0;
protected:
    int numberOfInterfaces;
};

Honeypot.cpp: Honeypot.cpp:

Honeypot::Honeypot(int numberOfInterfaces){
this-> numberOfInterfaces = numberOfInterfaces;
}

int Honeypot::getNumberOfInterfaces(){
return numberOfInterfaces;
}

Class Honeypot has child HoneypotV and HoneypotN. 类Honeypot有子HoneypotV和HoneypotN。 Now I created object with number of neteorkInterfaces: 现在,我创建了带有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;
}

In the main function: 在主要功能中:

NetworkType select;

Honeypot *p;

p = select.createObject(1,1,1);

cout << p->typeHoneypot() << endl;
cout << p-> getNumberOfInterfaces() << endl;

typeHoneypot() is correct, but getNumberOfInterfaces() returned value -858993460, correct is 3. typeHoneypot()是正确的,但是getNumberOfInterfaces()返回的值是-858993460,正确的是3。

Thank you for reply. 感谢您的回复。

You returning a pointer to local variable, but when you exit from your function, all local variables will be destroyed and pointer will reference to already destroyed object 您将返回指向局部变量的指针,但是当您退出函数时,所有局部变量将被销毁,并且指针将引用已销毁的对象

About code in main function: you declare a pointer to object and havent initialize it, so pointer points to some trash in memory 关于主函数中的代码:您声明一个指向对象的指针并没有对其进行初始化,因此该指针指向内存中的某些垃圾

You should dynamiclly instanciate the object if you want to return it : 如果要返回该对象,应动态实例化该对象:

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM