繁体   English   中英

C ++ const函数与参考

[英]C++ const function with reference

在此功能中:

(Counter是声明函数operator ++的类)

const Counter& operator++ ();

我的函数的const是什么意思? 我不太了解将const关键字与指针或引用结合使用!

这是一个运算符重载,但是声明语法类似于一个函数。 您的声明可以分为三部分:

  • 返回类型: const Counter&
  • 函数名称: operator++
  • 参数类型: () (无参数)

因此const Counter &告诉您该函数将返回对Counter对象的常量引用。 进行常量引用以使该对象无法被修改。

例如:

Counter c1;
++(++c1); // invalid

此处(++c1)返回对Counter对象的const reference 该引用已增加,但无效,因为该引用无法修改(它是恒定的)。

这意味着您不能使用此引用来更改其引用的对象。 例如,如果您有两个类型为Counter的对象

Counter obj1, obj2;

那你可能不会写

++obj1 = obj2;

因为由于限定符const,运算符++返回的引用所引用的对象是不可变的。

如果要在运算符声明中删除const限定符,则此语句

++obj1 = obj2;

将是有效的。

实际上,声明预增量运算符返回const引用不是一个好主意。 通常它声明时不带const限定符

Counter& opperator++ ();

在这种情况下,其行为与算术小数的预增量运算符++相同。 例如,此代码有效

int x = 1;

++ x = 2;

结果是x = 2;

为了说明我的评论,这里举一个例子:

class xy
{
private:
    int i; // const int i when object of xy is const
    int *ptr; // int *const ptr when object of xy is const

public:
    xy() : i(0), ptr(&i) { } // const i initialized to 0, only possible in constructor
                             // ptr pointing to i

    void set (int s) { i=s; } // changes i, not possible to define this member function
                              // as const like read()

    int read () const { return i; } // reads i

    void ptr_set (int s) const { *ptr = s; }
};

int main ()
{
    const xy obj;
    int read = obj.read(); // read() is allowed for const objects

    obj.set(10); // not allowed! you could not define set() as const (like read()):
                 // there would be a compiler error, because this member function
                 // would try to change const i

    obj.ptr_set(10); // allowed, would change i through pointer

    return 0;
}

顺便说一句,有人能解释为什么obj.ptr_set(10)在const正确性的意义上毕竟可行吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM