c++ - 如何在另一个类中调用类类型的向量?
问题描述
我得到了 main 并被告知创建一个程序来响应 main 使用 3 个类。游乐园班、骑手班和骑行班。我想将骑手添加到游乐设施向量中,并将该向量存储在游乐园向量中。我究竟做错了什么?我怎样才能解决这个问题?
#include <iostream>
#include <string>
using namespace std;
class Rider
{
string name;
int height;
public:
Rider(string name, int height)
{
this->name=name;
this->height=height;
}
Rider(int height)
{
this->height=height;
}
};
class Ride
{
public:
vector <Rider> all_riders;
};
class Amusement_park
{
vector <Ride> all_rides;
public:
Amusement_park(int numRides)
{
all_rides[numRides];
}
vector <Rider> get_ride(int whichRide)
{
vector <Ride> the_ride= all_rides[whichRide];
return the_ride;
}
void add_line(class Rider)
{
the_ride.pushback(Rider);
}
};
int main()
{
Rider r1("Yaris",45); //name, height in inches
Rider r2(49); //height in inches
Amusement_park a1(3); //3 is the number of rides in the park
a1.get_ride(1).add_line(r1); //add a rider to the line of a ride
Amusement_park a2(2); //2 is the number of rides in the park
a2.get_ride(1).add_line(r2); //add a rider to the line of a ride
return 0;
}
解决方案
我将为您的代码提供一些建议,其中一个(或多个)可能会解决您可能遇到的问题。
首先,尽可能尝试使用构造函数初始化列表。通常,当构造函数很明显时,使用这样的列表是微不足道的。在这种情况下,您可以这样做:
class Rider
{
string name;
int height;
public:
Rider(string name, int height) : name(name), height(height) {}
Rider(int height) : height(height) {}
};
其余的微不足道的构造函数也是如此。
现在,如果您仔细查看您的 c'torAmusement_park
类,您会发现您尝试访问您vector
尚未定义的索引。也就是说,您有一个空向量,它应该包含Ride
类型的对象,但由于它是空的,因此尝试访问其内容(您可能尝试访问的任何索引)就是我们所说的未定义行为。那是一块你不知道它持有什么的内存,那是因为你从来没有告诉你的编译器有多少Ride
对象将在那里,以便你的程序可以正确地分配内存并在那里为你初始化对象。为了让您实际创建适当大小的向量,或者更准确地说,正确调整向量的大小,您的Amusement_park
c'tor 应该是这样的
Amusement_park(int numRides)
{
all_rides.resize(numRides);
}
你get_ride
在游乐园里面的功能也不是很好。实际上,您的整个声明a1.get_ride(1).add_line(r1)
并没有按照您的意图进行。首先,该get_ride()
函数返回 a vector
of Rider
,它没有add_line()
成员函数。您实际上希望它返回一个Amusement_park
对象,这是您的代码中唯一具有这样一个成员函数的对象。但是,如您所见,返回它是不合逻辑的。
简而言之,您的代码包含许多缺陷,从逻辑上讲,这两种语言都是如此。因此,我建议您: 1)仔细检查代码的逻辑;2) 从一本不错的 C++ 教程开始。
祝你好运!
推荐阅读
- vb.net - 我正在向 word 文档中添加文本并且需要包含下标
- android - 如何从 DAO 查询中返回单个 int 值?
- javascript - 从 React 组件中的道具设置初始状态
- bash - 使用“$@”时脚本无法识别 Bash“-n”参数
- c# - StringFormat.Trimming 改变文本的垂直位置
- javascript - 在角度服务构造函数中订阅会阻止我的拖放功能
- java - 无法在 Selenium Java 中找到图像 xpath
- regex - 正则表达式获取字符串的开始和结束匹配
- docker - 在 $(docker-machine ...) 之前运行 eval 和 docker 之间的区别
- windows-subsystem-for-linux - 使用 wsl 运行多个命令