首页 > 解决方案 > 如何在另一个类中调用类类型的向量?

问题描述

我得到了 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;
}

标签: c++classoopobjectvector

解决方案


我将为您的代码提供一些建议,其中一个(或多个)可能会解决您可能遇到的问题。

首先,尽可能尝试使用构造函数初始化列表。通常,当构造函数很明显时,使用这样的列表是微不足道的。在这种情况下,您可以这样做:

    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_parkc'tor 应该是这样的

Amusement_park(int numRides)
    {
        all_rides.resize(numRides);
    }

get_ride在游乐园里面的功能也不是很好。实际上,您的整个声明a1.get_ride(1).add_line(r1)并没有按照您的意图进行。首先,该get_ride()函数返回 a vectorof Rider,它没有add_line()成员函数。您实际上希望它返回一个Amusement_park对象,这是您的代码中唯一具有这样一个成员函数的对象。但是,如您所见,返回它是不合逻辑的。

简而言之,您的代码包含许多缺陷,从逻辑上讲,这两种语言都是如此。因此,我建议您: 1)仔细检查代码的逻辑;2) 从一本不错的 C++ 教程开始。

祝你好运!


推荐阅读