c ++常量函数声明变量? [英] c++ constant function declaration variants?

查看:206
本文介绍了c ++常量函数声明变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下所有声明是否相同?如果是这样,声明一个常量函数的标准方法是什么?

Are all of the below declarations the same? If so, what is the standard way to declare a constant function?

const SparseMatrix transpose();

SparseMatrix transpose() const;

const SparseMatrix transpose() const;


推荐答案

函数名称左边的const表示返回的对象不能被修改。右边的const表示该方法是一个类的一部分,不修改它的任何数据成员。除非或者其任何数据成员用 mutable 关键字声明,在这种情况下允许修改它,尽管 const guard。

The const on the left of the function name means the object that is returned cannot be modified. The const on the right means the method is apart of a class and does not modify any of its data members. Unless or course any of its data members are declared with the mutable keyword, in which case modification thereof is permitted despite a const guard.

const 关键字的位置不重要,指针类型:

The placement of the const keyword is unimportant when the return type of the function is of non-pointer type:

 T const f(); // same as const T f();

但是,请注意 const 关键字在使用指针作为返回类型时很重要。例如:

However, note that the placement of the const keyword matters when using a pointer as the return type. For example:

const T* f();

此方法返回一个指向const T 。也就是说,它指向的是不可变的。因此,你不能通过取消引用返回的指针来做一个赋值:

This method returns a pointer to a const T. That is, what it points to is immutable. So you cannot do an assignment through a dereference of the returned pointer:

T* x = f();

*x = y; // error: assignment of read-only location '*(const T*)x'

T* const f();

int main()
{
    T* x const;

    x = f(); // error: assignment of read-only variable 'x'
}

我们在指针返回类型的两个两侧都有 const ,并且有 const 没有类成员的修改,那么它的读取如下:

Furthermore, if we have const on both sides of a pointer return type, and have const denoting "no modification of class members", then it's read as the following:

const T* const f() const;




一个名为 f ,它返回一个const指针指向一个const T

这篇关于c ++常量函数声明变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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