首页 > 解决方案 > How to properly pass a string through multiple child constructors to parent. C++

问题描述

I'm a college student in my first C++ class. I'm in need of some help for the current homework.

The goal I'm trying to accomplish is to create a new object (Rabbit) and pass the name pete from Rabbit > Mammal > Animal, to be set there privately and referenced later (The pointer is referenced later to print out the name).

string pete;
Rabbit* RabbitP = new Rabbit(pete);

I have the header file for Rabbit as so:

#include <string>

class Rabbit :
    public Mammal
{
public:
    Rabbit(std::string tempname) : Mammal(tempname){ }
    Rabbit();
    ~Rabbit();

I'm attempting to use the initialization list to pass the name of the Rabbit to Mammal, then to Animal from there. In the Mammal and Animal headers I have this:

#include <string>

class Mammal :
    public Animal
{
public:
    Mammal(std::string tempname) : Animal(tempname) {}
    Mammal();
    ~Mammal();
};

#include <string>

class Animal // BASE
{
private:
    std::string aName;
public:
    Animal(std::string tempname);
    Animal();
    ~Animal();

The Animal.cpp containing the function is:

#include <iostream>
#include <string>

using namespace std;

Animal::Animal()
{
}

Animal::~Animal()
{
}

Animal::Animal(string tempname)
{
    aName = tempname;
}

void Animal::Breathe()
{
    std::cout << "Takes a deep breath." << std::endl;
}

void Animal::Move()
{
    std::cout << "Jiggle your limbs around" << std::endl;
}

string Animal::GetName(Animal*)
{
    return aName;
}

Using the debugger in Visual Studio, I can see that it is moving up the constructors properly, but it is not passing anything. It feels like I'm somewhat on the right track, but what am I missing?

标签: c++c++11c++17

解决方案


string pete; 

这将调用string默认构造函数并创建一个空字符串。您现在在变量中有一个空字符串pete

Rabbit* RabbitP = new Rabbit(pete);

这将创建一个新的 Rabbit,调用构造函数并传递一个空字符串。您应该期望将 in 中的名称Animal设置为""

如果您希望名称为“Pete”,则调用它并传递字符串“Pete”。如果你不使用指针(这里看起来你不需要),它看起来像:

Rabbit RabbitP("Pete");

推荐阅读