简体   繁体   English

函数头/原型中const关键字的使用类型有什么区别?

[英]What are the differences in the types of usage of const keyword in function header/prototype?

What is the difference between the various usages of the const keyword in the function header/prototype?函数头/原型中const关键字的各种用法有什么区别?

    const int function(const int x) const;

Answer:回答:

The 1st const is to return by constant value shown here .第一个常量是通过此处显示的常量值返回。

The 2nd const is to have a constant function parameter shown here .第二个常量是这里显示的常量函数参数。

The 3rd const is used when the function is a class method/function that should only perform some sort of query operation such as get, hence should not change any of the class attributes/data variables shown here .当函数是类方法/函数时使用第三个常量,该类方法/函数应该只执行某种查询操作,例如 get,因此不应更改此处显示的任何类属性/数据变量。

const E& top() const throw(StackEmpty);

const E& is the return type of the function top() . const E&是函数top()的返回类型。 It is a reference to a constant E .它是对常量E的引用。

The const after the name of the function specifies, that the function won't modify the instance it is called upon and thus can be called on const -qualified instanced of the struct / class , top() is a member of. const名称后面的const指定,该函数不会修改它被调用的实例,因此可以在struct / class const限定实例上调用, top()是其成员。

The throw() -specification tells, that top() may throw an object of type StackEmpty . throw()规范告诉, top()可能抛出类型为StackEmpty的对象。 AFAIK such throw() -specifications naming a specific type are depreciated since C++11. AFAIK 此类throw()命名特定类型的规范自 C++11 起已贬值。

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

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