为什么使用const函数C ++时const冗余?

问题描述 投票:0回答:2

因此,我在C ++中遇到的所有修饰符都在函数名称之前。为什么const不同?为什么既要在名称之前又要在功能块之前?

const int getSize() const;

const int getSize const {
...
}
c++ const
2个回答
1
投票

[这是const关键字的2种不同用法。

在这种情况下:

const int getSize() { 

该函数正在返回一个int,即const,即返回值无法修改。 (这不是很有用,因为返回值很可能仍会被复制)。

在这种情况下:

int getSize() const { 

这是const限定的成员函数,即可以在const对象上调用此成员函数。同样,这保证了即使对象是非常量,也不会对其进行修改。

当然,您可以将两者同时使用:

const int getSize() const { 

这是一个const限定的成员函数,它返回const int


0
投票

函数之前的const应用于函数的返回类型。之后的const仅用于成员函数,表示该成员函数可在const对象上调用。

作为返回const int的注释没有意义,许多编译器会警告const被丢弃。

© www.soinside.com 2019 - 2024. All rights reserved.