Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/127.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 无法使用基类的方法_C++_Class_Inheritance_Methods - Fatal编程技术网

C++ 无法使用基类的方法

C++ 无法使用基类的方法,c++,class,inheritance,methods,C++,Class,Inheritance,Methods,可能重复: 似乎我不能直接使用派生类中的基类方法,如果它们在C++中的基类和派生类中都被重载。以下代码生成错误调用'Derived::getTwo()'时没有匹配的函数。 class Base { public: int getTwo() { return 2; } int getTwo(int, int) { return 2; } }; class Derived : public Base { public: in

可能重复:

<>似乎我不能直接使用派生类中的基类方法,如果它们在C++中的基类和派生类中都被重载。以下代码生成错误
调用'Derived::getTwo()'时没有匹配的函数。

class Base {
public:
    int getTwo() {
        return 2;
    }
    int getTwo(int, int) {
        return 2;
    }
};

class Derived : public Base {
public:
    int getValue() {
        // no matching function for call to ‘Derived::getTwo()’
        return getTwo();
    }
    int getTwo(int) {
        return 2;
    }
};
如果我更改
则返回getTwo()
返回((Base*)this)->getTwo()
,它可以工作,但在我看来这很难看。我怎样才能解决这个问题

另外,如果有必要,我使用g++4.7和选项std=gnu++c11。

或者:

class Derived : public Base {
public:
    using Base::getTwo; // Add this line
    int getValue() {
        // no matching function for call to ‘Derived::getTwo()’
        return getTwo();
    }
    int getTwo(int) {
        return 2;
    }
}


<>这是C++中名称查找的工作方式:

namespace N1
{
    int getTwo();
    int getTwo(int, int);

    namespace N2
    {
        int getTwo(int);

        namespace N3
        {
            call getTwo(something char*);
        }
    }
}
当前上下文是N3。此层上没有
getTwo
。好的,转到上层。N2包含一个
getTwo
的定义。编译器将尝试使用此定义,而不会搜索上层上下文。N2中的
getTwo
隐藏了所有上层上的
getTwo
的所有定义。有时,这会导致与重载方法的混淆


如果使用Base::getTwo添加
,实际上是将定义代理添加到内部上下文中。上部上下文标记的定义不可见。但是代理是可见的。

这肯定会作为副本关闭,但同时,快速的答案是使用Base::getTwo将
添加到类范围的
派生的
定义中。谢谢!你能解释一下为什么这也有效吗?或者更确切地说,为什么不这样做?@RPFeltz:它被称为隐藏,基本上这个过程是在最近的上下文中开始查找(从
getValue()
method+ADL内部开始),并尝试查找
getTwo()
,如果找不到,则检查下一个作用域,依此类推。一旦在一个上下文中找到标识符,它就会停止搜索。在您的例子中,它在类中查找
intgettwo(int)
,因此它不会在基类中查找其他重载。两种备选解决方案是:使用base::getTwo将基重载带到派生类作用域中,方法是
,以便在类中可用。。。。。。然后重载解析将选择最合适的重载。另一种解决方案是使用
base::getTwo()
限定调用,这将告诉编译器您想要从基类上下文中查找
getTwo()
(即,避免在当前范围内开始查找,并在
base
内跳转搜索
getTwo
namespace N1
{
    int getTwo();
    int getTwo(int, int);

    namespace N2
    {
        int getTwo(int);

        namespace N3
        {
            call getTwo(something char*);
        }
    }
}