c++中的继承,如何从派生类初始化基类中的成员变量



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

我有一个名为Person的类和三个从Person派生的类,名为:退休人员,成年人,孩子。

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

在java中,我只调用子类中的构造函数,因为它包含超类(a, b, c)。但是当我试着在这里做的时候,它不工作,我似乎不知道为什么。

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

当我尝试在LearnCPP.exe中创建对象"在0x759EA842处未处理异常:Microsoft c++异常:std::bad_alloc在内存位置0x00AFF514.">

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

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

Adult.h

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

Adult.cpp

#include "Adult.h"
Adult::Adult(double discount) : Person(age, name)
{
this->discount = discount;
}

Main.cpp

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

我认为这是你的问题:

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

你还没有向这个构造函数传递年龄或名字,所以它从父类中使用它们——父类的构造函数还没有被调用。

如前所述,您还没有传递name和age的值。

  1. 一个解决方案是,您可以更改构造函数以接受年龄和名称的值。
  2. 另一个解决方案是你可以定义默认构造函数。你也可以在参数化的构造函数中设置默认值。
Person::Person(int32_t age = 0, std::string name = ""){
this->age = age;
this->name = name; }

最新更新