c++继承 - 具有不同参数类型的相同方法名称

标签 c++ visual-studio-2010 visual-c++ inheritance

我正在尝试在 VC++ 2010 中编译以下代码:

class Base
{
public:
    std::wstring GetString(unsigned id) const
    {
        return L"base";
    }
};

class Derived : public Base
{
public:
    std::wstring GetString(const std::wstring& id) const
    {
        return L"derived";
    }
};

int wmain(int argc, wchar_t* argv[])
{
    Derived d;

    d.GetString(1);
}

我的理解是 Derived 有两种方法:

std::wstring GetString(unsigned id) const
std::wstring GetString(const std::wstring& id) const

所以我的代码应该可以成功编译。然而,Visual C++ 2010 报告以下错误:

test.cpp(32): error C2664: 'Derived::GetString' : cannot convert parameter 1 from 'int' to 'const std::wstring &'
      Reason: cannot convert from 'int' to 'const std::wstring'
      No constructor could take the source type, or constructor overload resolution was ambiguous

我做错了什么?当我以这种方式使用代码时,代码可以完美运行:

Derived d;
Base base = d;
base.GetString(1);

或者当 GetString 的两个变体在同一个类中定义时。

有什么想法吗?我想避免显式类型转换。

最佳答案

Derived::GetString 隐藏了 Base::GetString* 要解决此问题,请执行以下操作:

class Derived : public Base
{
public:
    using Base::GetString;

    std::wstring GetString(const std::wstring& id) const
    {
        return L"derived";
    }
};


* Scott Meyers 在“Effective C++”的第 50 章中解释了相当模糊的原因。

另见 http://www.parashift.com/c++-faq-lite/strange-inheritance.html#faq-23.9 .

关于c++继承 - 具有不同参数类型的相同方法名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8512088/

相关文章:

c++ - std::map 标准分配器性能与 block 分配器

c++ - 错误 C2668 对来自站点 http ://h264bitstream. sourceforge.net/的重载函数代码的模糊调用

c# - 防止屏幕捕获软件捕获应用程序屏幕

c++ - 堆栈链表中的弹出和推送函数

c++ - [[deprecated]] 在 Visual Studio 中导致错误而不是警告

c++ - 如何将枚举类型的数据保存到文件?

c# - Windows Azure 上的 Crystal 报表未显示

visual-studio-2010 - Visual Studio 2010 : highlight CSS text and comment

c++ - 如何判断哪些参数是必需的,哪些不是? (视觉 C++)

c++ - 由于 WTTlog.DLL 导致的运行时错误?