gpt4 book ai didi

c++ - (*rhs.m_pData) 的含义

转载 作者:行者123 更新时间:2023-11-28 03:06:56 26 4
gpt4 key购买 nike

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

我正在研究这段代码。

#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

在这种代码中,case 0-2 or other 你推荐哪种写法?

最佳答案

Does this mean the case 1 not case 2?

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

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

表示情况1。

In this kind of code, what kind of writing style do you recommend among case 0-2 or other?

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

关于c++ - (*rhs.m_pData) 的含义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19439688/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com