she*_*ngy 1 c++ inheritance operator-keyword
可能重复:
在C++中继承operator =的麻烦
我更新了代码
#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();
}
Run Code Online (Sandbox Code Playgroud)
我在评论中标出了这个问题,请给我一些帮助
它是由派生类继承.但是,派生类具有它自己operator =(由编译器隐含声明),它隐藏了operator =从父类继承的内容(在C++中搜索和读取"名称隐藏").
如果您希望继承operator =变为可见,则必须明确取消隐藏它
class Derive : public Base
{
std::string str;
public:
using Base::operator =; // unhide
};
Run Code Online (Sandbox Code Playgroud)
你的代码将编译.(如果您修复了明显的语法错误.请发布实际代码.)
PS这个问题经常被问到.我提供了一个更详细解释的链接,作为对您问题的评论.
| 归档时间: |
|
| 查看次数: |
355 次 |
| 最近记录: |