Here is the code, I wrote comments. The question is, I don’t know which function will be called after the unhide function 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 =;
};
int main(int argc, char *argv[])
{
Derive derive1;
derive1.num = 1;
Derive derive2;
Base b1;
derive1 = b1;
string str("test");
derive1 = str;
derive2 = derive1;
return 0;
}
But the result of the code is: derive2.num is 1 !!!, this means that the whole class was copied after the statement, 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 usage description in Derivewill be explained as follows:
class Derive : public Base
{
public:
int num;
Base& operator=(const Base &b);
Base& operator=(string& str);
Derive& operator=(const Derive &);
};
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.
source
share