首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >它会调用什么功能?

它会调用什么功能?
EN

Stack Overflow用户
提问于 2011-06-08 07:16:58
回答 2查看 117关注 0票数 3

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

代码语言:javascript
复制
    #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;
    }

但是代码的结果是:demve2.num等于1!,这意味着整个类都在状态之后被复制,为什么会发生这种情况呢?

多亏了托尼,我想我知道答案了。

这是我的解释:

基于C++0x 7.3.3.3和12.8.10,Derive中的using-语句将作如下解释

代码语言:javascript
复制
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
};

所以当我写到:

代码语言:javascript
复制
string str("test");
derive1 = str;

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

当我写到:

代码语言:javascript
复制
Base b1;
derive1 = b1;

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

最后,当我写道:

代码语言:javascript
复制
derive2 = derive1;

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-06-08 07:31:08

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

如果从基类引入派生类作用域的赋值操作符具有派生类的副本赋值操作符(class.copy)的签名,则使用-声明本身不会抑制派生类复制赋值操作符的隐式声明;基类中的复制赋值操作符被派生类的隐式声明复制赋值操作符隐藏或覆盖,如下所述。

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

票数 3
EN

Stack Overflow用户

发布于 2011-06-08 07:27:44

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6275383

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档