【问题标题】:Why am I able to modify object pointed by const reference为什么我能够修改 const 引用指向的对象
【发布时间】:2015-12-28 03:00:12
【问题描述】:
class Counter { 

int count;

void setCount() 
{
 this->count=10;
}

//declaration
friend  const Counter& operator+=( Counter &a, Counter &b); 
}
//definition
const Counter& operator+=(Counter &a, Counter &b) {

a.count = a.count + b.count;

return a;//returning reference to object a with const which makes object             //pointed by ref. a read only in calling function
 }

main() {
Counter c1,c2;
(c1+=c2);    
c1.setCount();     
}

main() 第 2 行:调用 operator+= 函数并获取对只读对象的引用,因为它返回 const Counter&

我的问题是, 在 main() 第 3 行:为什么我现在可以更改 c1 的状态/属性?我确实在 += 运算符中将它作为 const 引用返回。请解释一下

【问题讨论】:

    标签: c++ reference constants


    【解决方案1】:

    仅仅因为您的 operator+= 返回一个对 Counter 的 const 引用,它不会使 c1 成为一个 const Counter。

    如果您尝试执行 (c1+=c2).setCount(),那将失败,因为它会尝试在 operator+= 返回的对 c1 的 const 引用上调用非常量 setCount 方法

    旁注:operator+= 的第二个参数可能应该是一个 const 引用...

    【讨论】:

      【解决方案2】:

      c1 不是 一个常量。您在 main() 第 2 行将其声明为普通计数器,因此它是可修改的。

      该函数不被视为 const 函数,因为关键字不在末尾。使用 Counter& operator+=(Counter &a, Counter &b) const 以这种方式声明函数(编译时会出现错误,即 a.count = a.count + b.count; 不允许用于 const 对象)。

      【讨论】:

      • 由于函数被声明为朋友而不是成员,你实际上希望const Counter& operator+=(const Counter& a, Counter& b) 有一个常量
      • 谢谢 我想做的是返回对只读对象的引用。我尝试了一个成员函数 const int* getCount() {return &count;} 它给了我只读 int 在主。编译器还强迫我在 main() 中使用 const int* 而不是 int *。所以我想知道到底有什么区别。
      • 即使函数是const,后面的c1.setCount();还是合法的
      【解决方案3】:

      首先,如果所有C1 未声明为const-variable。 您在 main() 的第 2 行中所做的最终是在 C1 上调用 assignment 运算符,即 C1 = C1+C2。它接受Counter 类型的const-refernce - 但由于您没有定义赋值运算符,编译器会为您完成!因此,可以在C1 上调用非常量成员函数。

      【讨论】:

      • 第 2 行正在调用 operator+=,这是由 OP 定义的。无论如何,operator+= 没有隐含的定义。
      猜你喜欢
      • 1970-01-01
      • 2016-05-25
      • 2012-01-29
      • 1970-01-01
      • 2010-09-18
      • 1970-01-01
      • 2021-06-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多