Here is the code, I wrote the comments. The question is I don't know which function will be called after the function unhide in the Derive class.
#include <CONIO.H>
#include <IOSTREAM>
#include <string>
using namespace std;
class Base
{
string strName;
public:
Base& operator=(const Base &b)
{
this->strName = b.strName;
cout << "copy assignment" << endl;
return *this;
}
Base& operator=(string& str)
{
this->strName = str;
cout << "operator=(string& str)" << endl;
return *this;
}
};
class Derive : public Base
{
public:
int num;
using Base::operator =; // unhide Base::operator=();
};
int main(int argc, char *argv[])
{
Derive derive1;
derive1.num = 1;
Derive derive2;
Base b1;
derive1 = b1; // This will call Base& Base::operator=(const Base &b)
//no problem
string str("test");
derive1 = str; // This will call Base& Base::operator=(string& str)
// no problem
derive2 = derive1; // What function will this statement call???
// If it calls Base& Base::operator(const Base &b)
// how could it be assigend to a class Derive?
return 0;
}
But the result of the code is: derive2.num equals to 1!!!, that means the whole class has been copied after the statment, why would this happen?
Thanks to Tony, I think I got the answer.
here is my explanation:
Based on C++0x 7.3.3.3 and 12.8.10, The using-statement in Derive
will be explained like this
class Derive : public Base
{
public:
int num;
//using Base::operator =;
Base& operator=(const Base &b); // comes form the using-statement
Base& operator=(string& str); // comes form the using-statement
Derive& operator=(const Derive &); // implicitly declared by complier
};
So when I wrote:
string str("test");
derive1 = str;
function Base& Base::operator=(string& str);
will be called,
and when I wrote:
Base b1;
derive1 = b1;
function Base& Base::operator=(const Base &b);
will be called,
finnaly, when I wrote:
derive2 = derive1;
function Derive& Dervie::operator=(const Derive&);
will be called.
Standard 7.3.3-4 (from an old draft, but in this regard still valid):
If an assignment operator brought from a base class into a derived class scope has the signature of a copy-assignment operator for the derived class (class.copy), the using-declaration does not by itself suppress the implicit declaration of the derived class copy-assignment operator; the copy-assignment operator from the base class is hidden or overridden by the implicitly-declared copy-assignment operator of the derived class, as described below.
So, the implicit Derived::operator=()
is used.
It will call the derived operator=
, which in its automatically generated implementation will call operator=
from Base
as well as copy the members in Derive
.
精彩评论