本文介绍了为什么调用基类函数而不是派生函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堂课

class ProjectService : public CProjectT<CSoapMSXMLInetClient>
{
...
}

我已经在此派生类中实现了HRESULT ConnectToServer();函数.然后我实例化了一个对象并调用了一个函数:

I have implemented HRESULT ConnectToServer(); function in this derived class. Then I instantiated an object and called a function:

ProjectService project;
project.f1();

现在,f1()调用f2(),而f2()调用ConnectToServer().所有这些功能都是CProjectT<CSoapMSXMLInetClient>

now, f1() calls f2() and f2() calls ConnectToServer(). All of those functions are members of CProjectT<CSoapMSXMLInetClient>

这里的问题是,调用了CProjectT<CSoapMSXMLInetClient>::ConnectToServer()而不是ProjectService::ConnectToServer(). (我在两个ConnectToServer()函数的第一行上都有一个调试断点.命中了基类中的一个.)

The problem here is, CProjectT<CSoapMSXMLInetClient>::ConnectToServer() is called instead of ProjectService::ConnectToServer(). (I have a debug breakpoint on the first line of both ConnectToServer() functions. The one in base class is hit.)

为什么?

推荐答案

如上所述,您需要关键字virtual.为什么?因为仅在CProjectT中定义的函数f2()中会调用函数CProjectT<CSoapMSXMLInetClient>::ConnectToServer().如果没有virtual关键字,则f2()无法知道应该调用派生的方法.

As said, you need the keyword virtual. Why? Because in your function f2(), defined only in CProjectT, you call the function CProjectT<CSoapMSXMLInetClient>::ConnectToServer(). Without the virtual keyword, there is no way to know for f2() that the derived method should be called.

如果要测试:

#include <iostream>

using namespace std;

class Base
{
public:
    void f(){g();} // Wants to call Base::g() if there's no "virtual" keyword
    void g(){cout << "Base" << endl;}
    // virtual void g(){cout << "Base" << endl;}
};
class Derived : public Base
{
public:
    void g(){cout << "Derived" << endl;}
};

int main(int argc, char *argv[])
{
    Derived d;
    d.f();
}

这篇关于为什么调用基类函数而不是派生函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-27 20:54