C 超载和选择正确的功能

C++ overloading and picking right function

本文关键字:功能 选择 超载      更新时间:2023-10-16

c 方法问题问题

我有1个父级电话车辆

我有2个儿童班级摩托车和汽车

我有这个值调用getnoofwheels();

父班也有这种方法,摩托车和汽车也得到了。

说我提示用户输入

string vehicleType;
cout << "What is your vehicle type" << endl;
cin >> vehicleType;

基于用户输入,我如何使程序选择正确的功能基础,我知道我可以使用车辆==,但这是失败的目的。

提出了有关较早使用虚拟方法的建议。在这种情况下

virtual int noOfVerticles() const { return 0; }

用于shape.h

我在汽车和摩托车方

我尝试了这样的事情。

Vehicle cVehicle;
Car &rCar = &cVehicle;

if(inVehicle=="Car")
{
cout << rCar.noOfWheels() << endl;
}

我有一个错误,说..

invalid initizliation of non-const refenrece of type "Car&" from an rvaleu of type Vehicle*

和...

这是我在car.cpp

的虚拟功能
public:
virtual int noOfWheels() const { return 4; }

谢谢。!

Car &rCar = &cVehicle;

然后,您将rCar声明为参考,但您将其分配给 pointer 。anmpersand(&)根据使用的位置进行不同的操作。

当它在&cVehicle中使用时,它是运算符的地址,并将指针返回到cVehicle。当在变量声明中使用时,它告诉编译器该变量是参考。


至于您的问题,似乎您正在做一些错误的方法。使用虚拟方法时,您不必检查对象的类型,编译器将为您处理。

可以说您有此声明:

Vehicle *pVehicle = new Car;

现在,变量pVehicle是指向基类的指针,但是由于它被分配给了子类虚拟函数的指针,无论如何:

std::cout << "Number of wheels = " << pVehicle->noOfWheels() << 'n';

以上将打印车轮数为4,因为编译器将自动调用正确的功能。如果以后更改pVehicle指向Motorcycle实例,然后再次进行以上打印输出,则将正确地说2。

虚拟方法的全部要点是您能够通过统一方法调用来调用特定方法。

这在这样的内存中表示(这不是实际的内存布局,只是为了更好地想象):

[some class attribute]
[another class attribute]
[pointer to getNoOfWheels()]
[more class attributes]

当您在程序中调用noOfVerticles()时,它将调用[pointer to getNoOfWheels()]指向的任何指向(这与"正常呼叫"的相反,这将被调用到Vehicle::getNoOfWheels())。

创建Vehicle的实例:

[pointer to noOfVerticles] = Vehicle::getNoOfWheels()

如果创建CarBike,则将表示:

[pointer to noOfVerticles] = Car::getNoOfWheels()
[pointer to noOfVerticles] = Bike::getNoOfWheels()

假设您有以下类层次结构:

class Vehicle {
public:
    virtual int getNoOfWheels() const { return 0; } // Though this should be pure virtual method
}
class Car : public Vehicle {
public:
    virtual int getNoOfWheels() const { return 4; }
}
class Bike : public Vehicle {
public:
    virtual int getNoOfWheels() const { return 2; }
}

所以突然之间会发生:

Vehicle *one = new Vehicle(),
        *two = new Car(),
        *three = new Bike();
one->getNoOfWheels(); // Vehicle::getNoOfWheels() - thus 0
two->getNoOfWheels(); // Car::getNoOfWheels() - thus 4
three->getNoOfWheels(); // Bike::getNoOfWheels() - thus 2
// And you still call original method of a vehicle in car:
two.Vehicle::getNoOfWheels(); // 0

现在唯一要做的就是将正确的新实例分配给汽车,但这已经在Forevers的答案中涵盖了。

尝试使用..

Vehicle *vehicle1= new Car(); 
Vehicle *vehicle2= new MotorBike();

您可以调用函数vehicle1->getNoOfWheels()vehicle2->getNoOfWheels()。这将称为汽车和摩托车类的功能。这只有在您声明自己在基类工具中的虚拟功能时才发生。

同样适用于参考变量。