C – const成员/返回const int&vs返回int

前端之家收集整理的这篇文章主要介绍了C – const成员/返回const int&vs返回int前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
那些C线是什么意思?有没有替代方法来编写它们?
const int& a() const;
int getA() const;

谢谢.

解决方法

这两个是一个类中的成员函数的两个可能的签名,承诺不改变对象本身.在第一种情况下,它将返回一个常量引用到整数(可能是一个成员属性),引用是const意味着调用者将无法使用它来更改内部属性.第二种情况是按值返回一个整数.

在语义上有轻微的差异,但在大多数情况下,它们并不重要,将它们视为获取价值的两个功能.对于有所不同的情况,请看:

class test {
public:
   test() : m_value() {
      std::cout << &m_value << std::endl; // print where the attribute is
   }
   int const & getValue() const {
      return m_value;
   }
   int copyValue() const {
      return m_value;
   }
   void setValue( int value ) {
      m_value = value;
   }
private:
   int m_value;
};
int main() {
   test t;                      // will printout an address [1]
   int v1 = t.getValue();       // caller copies the value
   int v2 = t.copyValue();      // caller copies the value (itself a copy in hte calle)
   int const &r = t.getValue(); // reference to t.m_value
   int const &c = t.copyValue();// reference to *copy* [2]
   std::cout << v1 << v2 << r << c
      << std::cout;             // 0000
   std::cout << &v1 << &v2      // 4 pointers,the third is [1] a r *is* t.m_value
      << &r << &c << std::cout; //     the rest should be different
   t.setValue( 5 );
   std::cout << v1 << v2 << r   // 0050,v1 and v2 where copies,r *is* t.m_value
      << c << std::cout;
}

标有[2]的行使用语言的奇怪特征,如果您获得对r值(临时)的常量引用,编译器将将该临时参数绑定到引用,并保持其活动,直到引用超出范围(基本上将r值临时转换为隐藏变量,并将引用绑定到它).

我补充说,这一行是明确的,因为行为的差异不是由于接收端主要通过访问者的签名来保存引用的副本,而是(也是准确的).

原文链接:https://www.f2er.com/c/111647.html

猜你在找的C&C++相关文章