为什么operator =()函数不能由derive类继承

时间:2011-06-08 03:43:26

标签: c++ inheritance operator-keyword

  

可能重复:
  Trouble with inheritance of operator= in C++

我更新了代码

#include <QtCore/QCoreApplication>

class Base
{
    int num;
public:
    Base& operator=(int rhs)
    {
        this->num = rhs;
        return *this;
    }
};

class Derive : public Base
{
public:
    int deriveNum;
    using Base::operator =; // unhide the function
};

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    Base base;
    Derive derive1, derive2;

    base = 1;  // calls Base::operator(1) and returns Base&

    derive1 = 11; // calls Base::operator(11) and returns Base&
    derive2 = 22; // calls Base::operator(22) and returns Base&

    derive1 = base;// Which function does it calls??
               // If it calls Base::operator(base) and
                   // returns a Base&, how could it be assigend to derive1?

    return a.exec();
}

我在评论中标出了问题,请给我一些帮助

1 个答案:

答案 0 :(得分:9)

派生类继承了 。但是,派生类具有自己的operator =(由编译器隐式声明),隐藏从父类继承的operator =(搜索并读取“名称隐藏”在C ++)。

如果您希望继承的operator =可见,则必须明确取消隐藏

class Derive : public Base
{
  std::string str;

public:
  using Base::operator =; // unhide
};

并且您的代码将编译。 (如果您修复了明显的语法错误。请发布实际代码。)

P.S。这个问题经常被问到。我提供了一个更详细解释的链接,作为对您问题的评论。

相关问题