它会调用哪个功能?

时间:2011-06-08 07:16:58

标签: c++ inheritance operators operator-overloading

这是代码,我写了评论。 问题是我不知道在Derive类中取消隐藏函数后将调用哪个函数。

    #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;
    }

但是代码的结果是:derive2.num等于1 !!!,这意味着整个类已经在语句之后复制了,为什么会发生这种情况?

感谢Tony,我想我得到了答案。

这是我的解释:

基于C ++ 0x 7.3.3.3和12.8.10,Derive中的using语句将像这样解释

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
};

所以当我写道:

string str("test");
derive1 = str;

将调用函数Base& Base::operator=(string& str);

当我写道:

Base b1;
derive1 = b1;

将调用函数Base& Base::operator=(const Base &b);

finnaly,当我写道:

derive2 = derive1;

将调用函数Derive& Dervie::operator=(const Derive&);

2 个答案:

答案 0 :(得分:3)

标准7.3.3-4(来自旧草案,但在这方面仍然有效):

  

如果赋值运算符从基类带入派生类作用域,则具有派生类(class.copy)的复制赋值运算符的签名,则using-declaration本身不会抑制隐式声明派生类复制赋值运算符;来自基类的复制赋值运算符由派生类的隐式声明的复制赋值运算符隐藏或覆盖,如下所述。

因此,使用隐式Derived::operator=()

答案 1 :(得分:1)

它将调用派生的operator=,在其自动生成的实现中,它将从operator=调用Base并复制Derive中的成员。

相关问题