C 超载和选择正确的功能
C++ overloading and picking right function
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()
如果创建Car
或Bike
,则将表示:
[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()
。这将称为汽车和摩托车类的功能。这只有在您声明自己在基类工具中的虚拟功能时才发生。
同样适用于参考变量。
- 对可变参数使用声明.如何选择正确的功能
- 如果在VC6中使用打开功能,如何选择文件夹?
- c++ Visual Studio 2015 快捷方式,用于从选择代码中生成功能
- 在 Windows 上的C++中使用选择功能进行轮询
- 如何在类中实现可选择的类似命名空间的功能?
- 我的选择排序功能C 有什么问题
- 如何使用std ::有条件地选择一个免费功能
- 明智的选择是更喜欢lambdas功能对象
- QT:无法在ListBoxWidget中的ListBox项目中添加选择和取消选择功能
- 为什么C 编译器选择错误的功能(模板)
- 在不违反干prinicple的情况下,对传递功能对象的参数类型进行模板选择
- 我是否应该使用功能指针在构造函数中选择实现
- 选择何时使用好友功能
- 选择正确功能的更好方法
- 可以编译器告诉我它选择的哪个超载或模板功能
- unix中选择和轮询系统调用之间的功能差异
- C 超载和选择正确的功能
- 在模板功能和自动类型扣除之间进行选择
- 运行时的模板实例化和功能选择
- 如何使用AdaBoost进行功能选择