在类方法中使用c ++ const [英] c++ const use in class methods

查看:102
本文介绍了在类方法中使用c ++ const的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能的重复项:

这里的const有什么用

在类的函数中使用 const

大家好,

我一直在使用const与类方法和变量时犯错误。例如,有时我使用

Hi All,
I keep making mistakes about the use of const with class methods and variables. For example, sometimes I fix problems using

const int myfunc(const int &obj) const { }

另一些​​时候,由于参数已经是const了,所以我最后不需要const了,所以我不需要看看为什么我应该通过在末尾附加一个const来强制执行此事实。

some other times I feel I don't need const at the end since the parameter is already const, so I don't see why I should enforce this fact by appending a const at the end.

推荐答案

const int myfunc(const int& obj)const {}


  1. 第一个 const 表示返回值是恒定的。在这种情况下,它并不特别相关,因为 int 是一个值,而不是引用。

  2. 第二个 const 表示参数 obj 是常量。
  3. 第三个 const 表示函数 myfunc 是常量。这向调用者表明该函数将不会修改该函数所属类的不可更改成员变量。

  1. The first const indicates that the return value is constant. In this particular case, it's not particularly relevant since the int is a value as opposed to a reference.
  2. The second const indicates the parameter obj is constant. This indicates to the caller that the parameter will not be modified by the function.
  3. The third const indicates the function myfunc is constant. This indicates to the caller that the function will not modify non-mutable member variables of the class to which the function belongs.

关于# 3,考虑以下问题:

Regarding #3, consider the following:

class MyClass
{
    void Func1()       { ... }  // non-const member function
    void Func2() const { ... }  //     const member function
};

MyClass c1;        // non-const object
const MyClass c2;  //     const object

c1.Func1();  // fine...non-const function on non-const object
c1.Func2();  // fine...    const function on non-const object
c2.Func1();  // oops...non-const function on     const object (compiler error)
c2.Func2();  // fine...    const function on     const object

这篇关于在类方法中使用c ++ const的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆