c++ - 返回一个结构数组并在主类中使用

标签 c++

一些信息

Parent Class: Vehicle
Child Class: Car & Motorcycle

我有一个 struct

struct Point 
{
    int x,y;
};

我在 CarMotorcycle 上有一个 setPoint 函数,它执行以下操作

因为 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

所以我也得到了一个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。我不确定怎么了

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

最佳答案

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

另一种选择是使用 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是一种类型,而不是指向对象的指针。下次,将您的代码减少到最少并发布实际代码

关于c++ - 返回一个结构数组并在主类中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13098756/

相关文章:

c++ - 如何释放重新分配的内存? C++

c++ - float 到 SInt32

c++ - 将 gSOAP 与 2 个不同的 wsdl 文件一起使用时出现链接器错误

c++ - 如何修复此语句可能会通过 [-Werror=implicit-fallthrough=]?

android - 使用任意 Boost 库进行奇怪的 NDK 编译

C++使用find(str,index)计算字符串中char的出现次数

c++ - 如何按第一列在二维矩阵上使用 std::sort?

c++ - pthread读写锁是先进先出的吗?

c++ - 向库用户隐藏库依赖项

c++ - 这是三规则背后的正确逻辑吗?