开发者

Why is the following code giving me an error about an abstract class?

#include <iostream>
using namespace std;

class Vehicle
{
public:
    Vehicle() {};
    virtual ~Vehicle() {};
    virtual void Move() = 0;
    virtual void Haul() = 0;
};

class Car : public Vehicle
{
public:
    Car() {};
    virtual ~Car() {};
    virtual void Move(int m) { cDist = m;
    cout << "Vehicle moves " << cDist << " miles/hour\n"; }
    virtual void Haul() { cout << "Car's Hauling!\n"; }
private:
    int cDist;
};

class Bus : public Car
{
public:
    Bus() {};
    virtual ~Bus() {};
    void Move(int m) { Move(m); }
    void Haul() { "Bus is Hauling!\n"; }
};

int main()
{
    Vehicle* ptCar = new Car;
    Vehicle* ptBus = new Bus;
    ptCar->Move(1000);
    system("pause");
    return 0;
}

guys, why this code is giving me errors when trying to instantiate an object of Car, and Bus in main. I didn't intended to create an abstract class of Car and Bus, only of Vehicle... any help appreciated

1>------ Build started: Project: OperatorsTypes, Configuration: Debug Win32 -开发者_StackOverflow-----
1>  main.cpp
1>c:\users\jorge\documents\visual studio 2010\projects\shapes\operatorstypes\operatorstypes\main.cpp(36): error C2259: 'Car' : cannot instantiate abstract class
1>          due to following members:
1>          'void Vehicle::Move(void)' : is abstract
1>          c:\users\jorge\documents\visual studio 2010\projects\shapes\operatorstypes\operatorstypes\main.cpp(9) : see declaration of 'Vehicle::Move'
1>c:\users\jorge\documents\visual studio 2010\projects\shapes\operatorstypes\operatorstypes\main.cpp(37): error C2259: 'Bus' : cannot instantiate abstract class
1>          due to following members:
1>          'void Vehicle::Move(void)' : is abstract
1>          c:\users\jorge\documents\visual studio 2010\projects\shapes\operatorstypes\operatorstypes\main.cpp(9) : see declaration of 'Vehicle::Move'
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========


The Move function in your derived classes have a different signature (they both take an int).

To fix it, add an int parameter in the base class as well.

virtual void Move(int m) = 0


Car is abstract because it does not override the pure virtual void Vehicle::Move().

void Car::Move(int) does not override void Vehicle::Move() because its parameter list is different.


You are missing the parameter m in super class. In Vehicle

virtual void Move(int) = 0;  // add the int

In C++ with function overloading, aMethod() and aMethod(aArgument) are not same.


Move takes 0 arguments in the abstract Vehicle class and an int argument in Bus and Car so they are different functions. Change the prototype in Vehicle to

virtual void Move(int) = 0;


As the error indicates, Car and Bus are abstract because you did not override void Vehicle::Move() in them. Move(int) is a different function.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜