一些信息
Parent Class: Vehicle
Child Class: Car & Motorcycle
我得到了struct
struct Point
{
int x,y;
};
我在setPoint
和Car
获得Motorcycle
个功能执行以下操作的Car
因为Motorcycle
有4个轮子而Car
有2个轮子。
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;
}
功能..
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);
}
问题出在我的main.cpp上,我做了以下
{{1}}
无论是摩托车还是汽车,结果总是保持在4,摩托车不是2,汽车是4。我不确定什么是错的
假设我也为摩托车做了设定点。两者都返回相同的结果,是我在主类中包含Point myPoint不适合包含wheelPoint [array]
答案 0 :(得分:5)
sizeof(myPoint)
应返回类型Point
的大小(嗯,您的代码不会编译开始,但如果确实如此,那就是返回的内容)。 Car
和Motorcycle
不会被讨论。
另一种方法是让virtual
函数为Vechicle
:
class Vechicle
{
virtual int getNoWheels() = 0;
};
您在Car
和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
另一种方法是在std::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
是一个类型,而不是指向对象的指针。下次,将代码降至最低,发布实际代码。