C++派生类无法访问由构造函数初始化的基类成员

bvn4nwqk  于 2023-05-20  发布在  其他
关注(0)|答案(3)|浏览(146)

我是一个C新手,我刚开始学习类继承。我以前有一点C的指针和变量的经验,但不记得太多。
这就是我的问题。
所以我有两个类,一个基类和一个派生类
Base.h

#ifndef BASE_H
#define BASE_H

class Base {
protected:
    int* value_;
public:
    int* GetValue() { return value_; }
    void SetValue(int* value) { value_ = value; }
    Base() {
        int tmp = 5;
        SetValue(&tmp);
    }
};

#endif

Derived.h

#ifndef DERIVED_H
#define DERIVED_H

#include "Base.h"

class Derived : public Base {
public:
    Derived() { Base(); }
};

#endif

main.cpp

#include <iostream>

#include "base.h"
#include "derived.h"

int main() {
    Derived derived = new Derived();
    std::cout << derived->GetValue() << std::endl;
    return 0;
}

控制台输出

0

我做错了什么?控制台输出应该是5,对吗?

1l5u6lss

1l5u6lss1#

你的问题是你在不需要指针的时候使用了指针,最重要的是你使用的指针不正确。特别是,您将value_设置为指向tmp,但tmp是一个局部变量,一旦Base()构造函数返回,它就会被销毁,因此value_将成为一个悬空指针,当您稍后尝试通过GetValue()访问它时,您将调用未定义的行为。
您应该在代码中的任何地方将int*更改为int,并且也不要使用new运算符(在本例中不需要它,使用它会导致程序泄漏内存)。

ryevplcw

ryevplcw2#

要从子构造函数调用父构造函数,需要在初始化器列表中完成。例如:

class A;
class B : A
{
  B() : A() // <-- here
  {
  }
}

所以你的子类应该是这样的:

class Derived : public Base {
public:
    Derived() : Base() {  }
};
uplii1fm

uplii1fm3#

你的继承没有什么真正的问题,基本上是你的赋值中的一个错误
base.h

#ifndef BASE_H
#define BASE_H

class Base {
protected:
    int value;
public:
    int GetValue() { return this->value; }    
    Base(int value) {
        this->value = value;        
    }
};

#endif

derived.h

#ifndef DERIVED_H
#define DERIVED_H

#include "base.h"

class Derived : public Base {
public:
    Derived(int value):  Base(value){};
};

#endif

然后打电话说

auto derived = new Derived(7);
  std::cout << derived->GetValue() << std::endl;
  delete derived;

相关问题