0

一点资料

Parent Class: Vehicle
Child Class: Car & Motorcycle

我有struct一个

struct Point 
{
    int x,y;
};

我在&得到了一个setPoint函数,它执行以下操作CarMotorcycle

因为Car有 4 个轮子和Motorcycle2 个轮子。

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

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

Point Car::getPoint()
{
     return wheelPoint;
}

问题出在我的 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);
}

无论是摩托车还是汽车,结果始终保持在 4,摩托车不会是 2,汽车不会是 4。我不知道怎么了

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

4

1 回答 1

5

sizeof(myPoint)应该返回类型的大小Point(好吧,你的代码一开始就没有编译,但如果编译了,那就是它会返回的内容)。Car不要Motorcycle参与讨论。

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

class Vechicle
{
    virtual int getNoWheels() = 0;
};

Car您在and中覆盖Motorcycle

class Car : public Vechicle
{
    int getNoWheels() { return 4; }
};
class Motorcycle : public Vechicle
{
    int getNoWheels() { return 2; }
};

然后打电话。就像是:

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

vehicletwod[0]->getNoWheels(); //returns 4
vehicletwod[1]->getNoWheels(); //returns 2

另一种选择是将 astd::vector<Point>作为成员Vehicle

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

并根据实际类对其进行初始化,例如:

class Car
{
   Car() : Vehicle(4) {}
};

另外,我怀疑:

myPoint = Car->getPoint();

编译,因为Car它是一种类型,而不是指向对象的指针。下次,将您的代码减少到最低限度并发布实际代码

于 2012-10-27T09:15:52.477 回答