【问题标题】:How to understanding the meaning of C++03 13.5.3/2如何理解C++03的含义 13.5.3/2
【发布时间】:2011-12-15 02:43:27
【问题描述】:
#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>

struct B {
    virtual int operator= (int rhs)
    {
        m_iValue = rhs;
        return m_iValue;
    }

    virtual B& operator= (const B& rhs)
    {
        m_iValue = rhs.m_iValue;
        return *this;
    }

    int m_iValue;
};
struct D : B {
    virtual int operator= (int rhs)
    {
        m_iValue = rhs;
        return m_iValue;
    }

    virtual D& operator= (const B& rhs)
    {
        m_iValue = rhs.m_iValue;
        return *this;
    }
};

int _tmain(int argc, _TCHAR* argv[])
{
    D dobj1;
    D dobj2;
    B* bptr = &dobj1;

    bptr->operator=(99);     // calls D::operator=(int)
    *bptr = 99;              // ditto
    bptr->operator=(dobj2);  // calls D::operator=(const B&)
    *bptr = dobj2;           // ditto
    dobj1 = dobj2;           // calls implicitly-declared
                             // D::operator=(const D&)
    return 0;
}

问题1>此问题可能与问题2&3有关。

参考:C++03 13.5.3/2

注意:对于具有基类 B 的派生类 D,其虚拟 已声明复制赋值,D 中的复制赋值运算符 不会覆盖 B 的虚拟副本赋值运算符。

以下语句用简单的英语是什么意思?

D 中的复制赋值运算符不会覆盖 B 的虚拟副本 赋值运算符。

问题2>为什么下面的语句调用`D::operator=(int)

    *bptr = 99;              // ditto

问题3>为什么下面的语句调用隐式D::operator=(const D&amp;)

    dobj1 = dobj2;           // calls implicitly D::operator=(const D&)

【问题讨论】:

  • 对于第二季度和第三季度,您或许应该解释您预期会发生什么以及原因。

标签: c++


【解决方案1】:

问题 1。 对于B,复制赋值运算符是B::operator=(const B&amp;) 或类似的。对于D,它是D::operator=(const D&amp;)。一个不能覆盖另一个,因为参数类型不同。

【讨论】:

  • 除了...对于 D 它是 D::operator=(const B&amp;) 所以参数类型是相同的。但是,返回类型不同。
  • 复制赋值运算符,根据定义,采用与左侧相同类型的参数。所以你的operator= 不是复制作业。只是一个任务。
猜你喜欢
  • 1970-01-01
  • 2013-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-22
  • 1970-01-01
相关资源
最近更新 更多