如何理解c++ 03 13.5.3/2的含义

How to understanding the meaning of C++03 13.5.3/2

本文关键字:何理解 c++      更新时间:2023-10-16
#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&)

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

问题1。对于B,拷贝赋值操作符为B::operator=(const B&)或类似的操作符。对于D,是D::operator=(const D&)。一个不能覆盖另一个,因为参数类型不同。