Why can't the operator=() function be inherited by the derive class [duplicate]
Possible Duplicate:
Trouble with inheritance of operator= in C++
I updated the code
#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();
}
I marked the question in the comment, please give me some more help
It is inherited by the derived class. However, the derived class has it own operator =
(implictly declared by the compiler), which hides the operator =
inherited from the parent class (search and read about "name hiding" in C++).
If you want the inherited operator =
to become visible, you have to explicitly unhide it
class Derive : public Base
{
std::string str;
public:
using Base::operator =; // unhide
};
and your code will compile. (If you fix the obvious syntax errors that is. Please, post real code.)
P.S. This question is asked very often. I provided a link to a more detailed explanation as a comment to your question.
精彩评论