首页 > 解决方案 > C++中的继承,如何从派生类初始化基类中的成员变量

问题描述

我今天几乎是第一次打开 C++,我尝试做一些继承。

我有一个名为 Person 的类和三个派生自 Person 的类:Retiree、Adult、Child。

控制台询问您的年龄,如果您在控制台中输入 30,我想制作一个新的成人对象,在这里我想传入参数:年龄、姓名和折扣。

在 java 中,我只调用子类中的构造函数,因为它有 super(a, b, c) 。但是当我在这里尝试这样做时,它不起作用,我似乎无法弄清楚为什么。

下面是 Person 和 Adult 的两个 cpp 文件,显示了它们的构造函数,最后是 Main.cpp

当我尝试创建对象“LearnCPP.exe 中 0x759EA842 处的未处理异常:Microsoft C++ 异常:内存位置 0x00AFF514 处的 std::bad_alloc”时出现此错误。

人.h

#pragma once
#include <String>
#include "BudgetAccount.h"
class Person
{

private:


public:
    Person(int32_t age, std::string name);

    int32_t getAge();

    void setAge(int32_t age);

    std::string getName();

    void setName(std::string name);

protected:
    int32_t age;
    std::string name;

};

个人.cpp

#include "Person.h"
#include <String>

Person::Person(int32_t age, std::string name)
{
    this->age = age;
    this->name = name;
}



int32_t Person::getAge() 
{

    return age;
}

void Person::setAge(int32_t age)
{
    this->age = age;
}

std::string Person::getName()
{
    return name;
}

void Person::setName(std::string name)
{
    this->name = name;
}

成人.h

#pragma once
#include "Person.h"
class Adult : public Person
{
private:
    double discount;

public:
    Adult(double discount);
};


成人.cpp

#include "Adult.h"

Adult::Adult(double discount) : Person(age, name)
{
    this->discount = discount;
}

主文件

#include <iostream>
#include "Person.h"
#include "Adult.h"

int main()
{
    std::cout << "Hello Customer" << std::endl;
    std::cout << "Down below you see a list of cities" << std::endl;
    std::cout << "Please enter your name" << std::endl;
    //Cin 
    std::string name;
    std::cin >> name;

    std::cout << "Please enter your age" << std::endl;
    
    std::int32_t age;
    std::cin >> age;

    //Check if the entered age is child, adult or retiree
    
    Adult user(50.0);
    
    std::cout << "Please select which city you want to travel to" << std::endl;

    return 0;
}

标签: c++inheritance

解决方案


我认为这是你的问题:

Adult::Adult(double discount) : Person(age, name)
{
    this->discount = discount;
}

您还没有将年龄或名称传递给此构造函数,因此它正在使用父类中的它们——尚未调用其构造函数。


推荐阅读