C++ 虚函数,为什么在这里调用基类函数?

C++ 虚函数,为什么在这里调用基类函数?,c++,virtual-functions,C++,Virtual Functions,有人能帮我一下我做错了什么吗?始终调用基类指针!我正在尝试创建自定义类对象的映射。也尝试了直接查找和索引,但结果相同 #include "stdafx.h" #include <iostream> #include <string> #include <Map> #include <algorithm> class Command { public: virtual int execute(std::string *args) { std

有人能帮我一下我做错了什么吗?始终调用基类指针!我正在尝试创建自定义类对象的映射。也尝试了直接查找和索引,但结果相同

#include "stdafx.h"
#include <iostream>
#include <string>
#include <Map>
#include <algorithm>

class Command
{
public:
    virtual int execute(std::string *args) { std::cout << "Base called ! ERROR!\n"; return -1; }
};

class ShowNames : public Command
{
public:
    int execute(std::string names)
    {
        std::cout << names;
        return 0;
    }
};

class ShowNos : public Command
{
public:
    int execute(std::string Nos)
    {
        std::cout << Nos;
        return 0;
    }
};

typedef std::map<std::string, Command*> CmdList;

CmdList buildMaps()
{
    CmdList c1;
    ShowNames s1;
    ShowNos   n1;

    c1["names"] = new ShowNames();
    c1["nos"] = new ShowNos();

    //c1.find("names")

    return c1;
}

void testCommandList()
{
    CmdList commands;
    Command *c1;
    commands = buildMaps();

    std::string cmd,args;
    std::cout << "Enter your command: ";
    std::cin >> cmd;
    std::cout << "Enter args for the command: ";
    std::cin >> args;

     auto it = commands.find(cmd);
     if (it != commands.end())
     {
         it->second->execute(&args);
     }
     else
     {
         std::cout << "Command not found, try again\n";
     }

}

您不是在派生类中重写基函数,而是在声明新函数。比较函数类型:

int   Command::execute(std::string *args)
int ShowNames::execute(std::string  names)
int   ShowNos::execute(std::string  Nos)
调整以使其更加明显

若要重写基类函数,必须完全匹配签名,协变返回类型除外(如果需要)。因此,将签名更改为相同。当然,哪一个是正确的取决于你的问题领域

这就是为什么C++11引入了保留字覆盖,您可以将它放在一个虚拟函数上,您打算覆盖一个基类函数。如果不是这样,它将导致编译错误。如果您有权访问C++11,那么您应该始终使用它,就像这样:

class ShowNames : public Command
{
public:
    int execute(std::string names) override
    {
        std::cout << names;
        return 0;
    }
};

这将立即告诉您,它不会覆盖任何基类函数,您可以更好地开始调查原因。

您不是在派生类中覆盖基类函数,而是在声明新函数。比较函数类型:

int   Command::execute(std::string *args)
int ShowNames::execute(std::string  names)
int   ShowNos::execute(std::string  Nos)
调整以使其更加明显

若要重写基类函数,必须完全匹配签名,协变返回类型除外(如果需要)。因此,将签名更改为相同。当然,哪一个是正确的取决于你的问题领域

这就是为什么C++11引入了保留字覆盖,您可以将它放在一个虚拟函数上,您打算覆盖一个基类函数。如果不是这样,它将导致编译错误。如果您有权访问C++11,那么您应该始终使用它,就像这样:

class ShowNames : public Command
{
public:
    int execute(std::string names) override
    {
        std::cout << names;
        return 0;
    }
};

这将立即告诉您,它不会覆盖任何基类函数,您可以更好地开始调查原因。

您从未真正覆盖过基类方法

virtual int execute(std::string *args)

这是签名。您需要坚持使用它,而不是更改它。

您永远不会覆盖您的基类方法

virtual int execute(std::string *args)

这是签名。你需要坚持,而不是改变它。

我不知道这一点,谢谢你提供的信息!!我不知道,谢谢你提供的信息!!