The meaning of (*rhs.m_pData)

The meaning of (*rhs.m_pData)

本文关键字:pData rhs meaning of The      更新时间:2023-10-16

我想确定我的理解是否正确。

我正在研究这段代码。

#include <iostream>
using namespace std;
// modified largely from
// http://d.hatena.ne.jp/toburau/20090722/1248283158
/*
class Test {
public:
    Test& operator=(const Test& rhs);
};
Test& Test::operator=(const Test& rhs)
{
    if (this == &rhs) return *this;          // *****
};
*/
//-----------------------------------------------------
class Data
{
    int num;
public:
    Data(void) : num(0) { }
    Data(int _num) : num(_num) { }
    Data(const Data &rhs) {
        cout << "copy constructor is called" << endl;
        num = rhs.num;
    }
    void show(void) {
        cout << num << endl;
    }
};
class CopyTest {
    Data *m_pData;
public:
    CopyTest(void) {
        m_pData = new Data(0);
    }
    CopyTest(int _num) {
        m_pData = new Data(_num);
    }
    void show(void) {
        m_pData->show();
    }
    CopyTest& operator=(const CopyTest& rhs);
};
CopyTest& CopyTest::operator=(const CopyTest& rhs) /*****/
{
    Data *p = m_pData;
    m_pData = new Data(*rhs.m_pData); // case 0 // OK // copy constructor is called
//  m_pData = new Data(*(rhs.m_pData)); // case 1 // OK
//  m_pData = new Data(*(rhs).m_pData)); // case 2 // NG
    delete p;
    return *this;
}

int main() {
    CopyTest cpyObjA, cpyObjB(31);
    cpyObjA.show();
    cpyObjB.show();
    cout << "## after" << endl; 
    cpyObjA = cpyObjB;
    cpyObjA.show();
    cpyObjB.show();
    return 0;
}

看http://ideone.com/7qnzLP对于带有行号和颜色的代码。

在此代码(第 53 行)中,有类似

 m_pData = new Data(*rhs.m_pData); // case 0

这是否意味着案例 1 而不是案例 2?

 m_pData = new Data(*(rhs.m_pData)); // case 1
 m_pData = new Data(*(rhs).m_pData); // case 2

在这种代码中,您推荐哪种情况 0-2 或其他写作风格?

这是否意味着案例 1 而不是案例 2?

m_pData = 新数据(*(rhs.m_pData));//案例 1

m_pData = new Data(*(rhs).m_pData);//案例 2

它意味着案例 1。

在这种代码中,您推荐哪种情况 0-2 或其他写作风格?

我总是避免多余的括号,实际上是多余的任何东西。

您的case 1case 2相同。在 c++ 中,'.' operator 的优先级高于 '*' operator ,括号不会更改优先级。case 1case 2都是对的。我以为你想说的是 m_pData = new Data((*rhs).m_pData);,这是错误的。您可以阅读运算符优先级表:level.http://en.cppreference.com/w/cpp/language/operator_precedence