【问题标题】:c++ inheritance - same method name with different argument typec ++继承-具有不同参数类型的相同方法名称
【发布时间】:2011-12-14 21:44:25
【问题描述】:

我正在尝试在 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 的两个变体都定义在同一个类中时。

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

【问题讨论】:

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


    【解决方案1】:

    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

    【讨论】:

    • +1 或者,您可以手动选择方法:d.base::GetString(1),但这具有禁用动态调度的令人讨厌的副作用(如果成员函数是 virtual,则情况并非如此)跨度>
    • 使用 Base::GetString 非常有意义。我认为编译器更智能一些,只有当基类和派生方法的参数以某种方式兼容时才会抛出这样的错误。
    • 顺便说一句,这也解释了为什么我不能在派生类中调用“base”GetString 而不显式键入 Base::GetString 或 __super::GetString。
    猜你喜欢
    • 2015-03-20
    • 2020-10-18
    • 1970-01-01
    • 2011-05-29
    • 1970-01-01
    • 1970-01-01
    • 2011-01-23
    • 1970-01-01
    相关资源
    最近更新 更多