虚拟课堂有什么好处?
可能的重复:
C++ 虚拟/纯虚拟解释
例如,我有:
class A {
private:
int i;
int j;
public:
void k (int l, int m) { i=l; j=m; }
virtual int n (void);
};
class B : public A {
public:
int n (void);
};
这个虚拟有什么好处?
Possible Duplicate:
C++ Virtual/Pure Virtual Explained
For example i have:
class A {
private:
int i;
int j;
public:
void k (int l, int m) { i=l; j=m; }
virtual int n (void);
};
class B : public A {
public:
int n (void);
};
What good is this virtual ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我喜欢用国际象棋游戏作为例子:
AICode() 不需要知道它正在看哪一个棋子。
它所做的只是要求棋子看看它的最佳着法是什么。虚拟调度机制将计算出棋子的类型并调用正确的 Move() 方法。
I like to use the Chess Game as an example for this:
The AICode() does not need to know which piece it is looking at.
All it does is ask the piece to see what its best move is. The virtual dispatch mechanism will work out the type of piece and call the correct Move() method.
它是为了引发多态行为,这意味着客户端可以使用单个合约来调用不同的行为,而客户端不必了解每种可能的行为。
作为一个更具体的例子,这里有一些相当刻板的代码:(
免责声明:上面的代码既不正确也不完整,并且当然不能作为良好图形代码的示例。它只是为了说明虚函数何时有用。
It's to induce polymorphic behaviour, which means that a single contract can be used by a client to invoke different behaviours, without the client having to know about every possible behaviour.
As a more concrete example, here some fairly stereotypical code:
(Disclaimer: The above code is neither correct nor complete, and is certainly not to be held up as an example of good graphics code. It's just to illustrate when virtual functions are useful.
我建议您参考这个关于多态性的优秀SO页面。
I refer you to this excellent SO page about polymorphism.