当然,在某些情况下,编译器足够聪明,可以准确推断出您想要的功能,而其他情况又需要运行时支持吗?
因为我们并不总是知道,所以在运行时我们将面对哪个实例。
例如,你有类:SuperClass
,Subclass1
并且Subclass2
,他们都有一个方法doACoolThing()
。用户按下一个按钮0
,1
或2
,并根据他的输入,创建相应的类的一个实例,它的doACoolThing()
方法被调用。
我们(以及编译器)也无法确定在运行时将调用哪种类的方法。
这就是为什么这些技巧需要运行时支持的原因。
一个小例子来说明一个想法(PS不写这样的代码,它只是在说明多态性:)):
#include <iostream>
using namespace std;
class SuperClass
{
public:
virtual void doACoolThing();
};
void SuperClass::doACoolThing()
{
cout << "Hello from the SuperClass!" << endl;
}
class Subclass1 : public SuperClass
{
virtual void doACoolThing() override;
};
void Subclass1::doACoolThing()
{
cout << "Hello from the Subclass1" << endl;
}
class Subclass2 : public SuperClass
{
virtual void doACoolThing() override;
};
void Subclass2::doACoolThing()
{
cout << "Hello from the Subclass2" << endl;
}
int main()
{
int userInput;
cout << "Enter 0, 1 or 2: ";
cin >> userInput;
SuperClass *instance = nullptr;
switch (userInput)
{
case 0:
instance = new SuperClass();
break;
case 1:
instance = new Subclass1();
break;
case 2:
instance = new Subclass2();
break;
default:
cout << "Unknown input!";
}
if (instance)
{
instance->doACoolThing();
delete instance;
}
return 0;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句