const是什么意思在c ++在不同的地方 [英] what does const mean in c++ in different places

查看:104
本文介绍了const是什么意思在c ++在不同的地方的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    const string& getName() const {return name;}

    string& getName() const {return name;}



What does const mean at the beginning and at the end?

推荐答案

函数签名结尾处的 const 是一个常数成员函数,所以你的方法都是const成员函数。

The const at the end of the function signature means the method is a const member function, so both your methods are const member functions.

const 在开头意味着返回的是const。

The const at the beginning means whatever is being returned is const.

第一个例子是一个const方法返回一个const引用内部数据,因此是const正确的。

The first example is a const method returning a const reference to internal data, and is therefore const-correct.

第二个是一个const方法返回内部数据的非const引用。这不是const正确的,因为它意味着你将能够修改一个const对象的数据。

The second is a const method returning non-const reference to internal data. This is not const-correct because it means you would be able to modify the data of a const object.

一个方法的调用不能改变任何实例数据(可变数据成员除外),并且只能调用其他const方法。

A call to a const a method cannot change any of the instance's data (with the exception of mutable data members) and can only call other const methods.

const方法可以在const或非const实例上调用,方法只能在非const实例上调用。

Const methods can be called on const or non-const instances, but non-const methods can only be called on non-const instances.

这篇关于const是什么意思在c ++在不同的地方的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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