c++ - 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?
解决方案
string pete;
这将调用string
默认构造函数并创建一个空字符串。您现在在变量中有一个空字符串pete
。
Rabbit* RabbitP = new Rabbit(pete);
这将创建一个新的 Rabbit,调用构造函数并传递一个空字符串。您应该期望将 in 中的名称Animal
设置为""
。
如果您希望名称为“Pete”,则调用它并传递字符串“Pete”。如果你不使用指针(这里看起来你不需要),它看起来像:
Rabbit RabbitP("Pete");
推荐阅读
- node.js - 如何将日期作为输入传递给节点中的 SQL Server 查询
- docker - 无法使用在 Docker 上运行的 Kafka 和 Zookeeper 创建 Kafka 主题
- javascript - 用户使用javascript单击图像后如何启用按钮
- python - 加载和读取 JSON 文件的正确方法包含 Python 中的特殊字符
- html - 绝对位置不适用于引导下拉菜单
- c# - 在 C# 中获取对字段值的引用
- reactjs - React Typescript - 处理具有多个字段的对象的表单更改
- java - StaggeredGridLayoutManager 正在显示像 GridLayoutManager 这样的图像
- javascript - 反应节点身份验证
- html - method="post" 和 type="submit" (HTML) 有什么区别?