返回一个struct数组并在main类中使用

use*_*711 0 c++

一点信息

Parent Class: Vehicle
Child Class: Car & Motorcycle
Run Code Online (Sandbox Code Playgroud)

我有一个struct

struct Point 
{
    int x,y;
};
Run Code Online (Sandbox Code Playgroud)

我得到了一个setPoint功能,在CarMotorcycle其执行以下操作

因为Car有4个轮子,Motorcycle有2个轮子.

Car 将有这个功能

class Car : public Vehicle
{
private:
    Point wheelPoint[4]; // if motorcycle then its wheelPoint[2]
public:
    Point getPoint();
    void setPoint();
}

void Car::setPoint()
{
    int xData,yData;

    for (int i=0;i<4;i++)
    {
         cout << "Please enter X  :" ;
         cin >> xData;
         cout << "Please enter Y  :" ;
         cin >> yData;
    }//end for loop
}//end setPoint
Run Code Online (Sandbox Code Playgroud)

所以我也有一个getPoint功能..

Point Car::getPoint()
{
     return wheelPoint;
}
Run Code Online (Sandbox Code Playgroud)

问题发生在我的main.cpp,我做了以下几点

int main()
{
     VehicleTwoD *vehicletwod[100];

     //assuming just car but there motorcycle too
     Car *mCar = new Car();
     Point myPoint;

     vechicletwod[0] = mCar;
     //here i did the setpoint, set other variable

     //then when i try retrieve
     myPoint = Car->getPoint();
     //no error till here.

     cout << sizeof(myPoint);
}
Run Code Online (Sandbox Code Playgroud)

无论是摩托车还是汽车,结果总是保持在4,摩托车不是2,汽车是4.我不确定什么是错的

假设我也做了摩托车的设定点.两者都返回相同的结果,是我在主类中包含Point myPoint不适合包含wheelPoint [array]

Luc*_*ore 5

sizeof(myPoint)应该返回类型的大小Point(好吧,你的代码不会编译开始,但是如果它做了,那就是它将返回的内容).Car并且Motorcycle不要讨论.

一种替代方案是具有以下virtual功能Vechicle:

class Vechicle
{
    virtual int getNoWheels() = 0;
};
Run Code Online (Sandbox Code Playgroud)

你重写的内容CarMotorcycle:

class Car : public Vechicle
{
    int getNoWheels() { return 4; }
};
class Motorcycle : public Vechicle
{
    int getNoWheels() { return 2; }
};
Run Code Online (Sandbox Code Playgroud)

然后打电话.就像是:

VehicleTwoD *vehicletwod[100];
vehicletwod[0] = new Car;
vehicletwod[1] = new Motorcycle;

vehicletwod[0]->getNoWheels(); //returns 4
vehicletwod[1]->getNoWheels(); //returns 2
Run Code Online (Sandbox Code Playgroud)

另一种选择是std::vector<Point>成为一名成员Vehicle:

class Vehicle
{
   std::vector<Point> wheels;
   Vehicle(int noWheels) : wheels(noWheels) {}
   int getNoWheels() { return wheels.size() }
};
Run Code Online (Sandbox Code Playgroud)

并根据实际类初始化它,例如:

class Car
{
   Car() : Vehicle(4) {}
};
Run Code Online (Sandbox Code Playgroud)

另外,我怀疑:

myPoint = Car->getPoint();
Run Code Online (Sandbox Code Playgroud)

compiles,因为它Car是一个类型,而不是指向对象的指针.下次,将代码减少到最小并发布实际代码.