The meaning of (*rhs.m_pData)
The meaning of (*rhs.m_pData)
我想确定我的理解是否正确。
我正在研究这段代码。
#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 1
与case 2
相同。在 c++ 中,'.' operator
的优先级高于 '*' operator
,括号不会更改优先级。case 1
和case 2
都是对的。我以为你想说的是 m_pData = new Data((*rhs).m_pData);
,这是错误的。您可以阅读运算符优先级表:level.http://en.cppreference.com/w/cpp/language/operator_precedence
相关文章:
- Widget&&rhs 是左值还是右值引用
- C++ 运算符"="重载 - 在 lhs 上获取向量中的所有值,使其等于 rhs 上的双精度值
- C++11+=当RHS有多个字符串或字符时,运算符不起作用
- 当找到来自 RHS 的字符"\"时,从主字符串中获取单词或子字符串,然后擦除其余部分
- 什么是 lhs/rhs 以及如何在此程序中使用它
- 有没有办法禁用 MSVC 输出中的".pdata"/"ExceptionDir"和"UNWIND_INFO"?
- RHS 运算符重载
- 析构函数是移动ctor/赋值的RHS上唯一调用过的东西吗
- 误报警告 PVS 工作室:V821 性能降低。'rhs'变量可以在较低级别的范围内构造
- RHS如何工作
- reduce函数的第二个rhs参数中tbb::parallel_reduce:constness的Lambda形式
- 运算符+=可以调用自己,但"*this"与"rhs"交换吗?
- 如何将XMFLOAT3转换为常量浮点数 *pData
- 在llvm中获取ICmpInst和FCmpInst的LHS和RHS
- The meaning of (*rhs.m_pData)
- 将模板化适配器编译错误作为运算符重载实例的 rhs
- 通过友元函数重载运算符,并返回与rhs参数不同的类型
- Dog复制构造函数[:Mammal(rhs)]中声明的内容
- 如何创建一个合适的布尔值 员工::运算符==(const Employee & rhs) const
- 无法从'const Eigen::GeneralProduct<Lhs,Rhs,ProductType>'转换为'double'