函数声明中以及其他位置的&符号右侧的C ++ const [英] C++ const to the right of the ampersand in a function declaration and everywhere else

查看:49
本文介绍了函数声明中以及其他位置的&符号右侧的C ++ const的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此:

void foo(const std::string & bar);

具有与此相同的含义:

void foo(std::string const& bar);

1.)但是,如果我这样做,会发生什么事?

1.) But what happens if I do this:

void foo(std::string &const bar);

这是否意味着参数本身的地址是常量?你为什么要这样做?

Does it mean the address to the parameter itself is constant? Why would you do this?

2.)此外,如果我这样做会发生什么情况:

2.) Furthermore what happens if I do this:

void foo(const std::string const& bar);

void foo(std::string & bar const);

?

推荐答案

std::string &const bar

表示 bar 是对(非恒定)字符串的恒定引用.这没有任何意义,因为您仍然无法更改参考.这也是无效的,因为引用类型不能为常数.

would mean that bar is a constant reference to a (non-constant) string. It doesn't make any sense since you can't change a reference anyway. It's also not valid as a reference type can't be constant.

在其中放置 const 会起作用并且有意义的情况是使用指针时,例如

A case where placing the const there would work and also make sense is when using pointer, like e.g.

std::string * const bar

这意味着 bar 是指向(非恒定)字符串的恒定指针.变量 bar 是常量,您不能在其他任何地方指向 bar .示例:

This means that bar is a constant pointer to a (non-constant) string. The variable bar is constant, and you can not make bar point anywhere else. Example:

std::string * const bar = new std::string("foo");
bar = new std::string("bar");  // Invalid as `bar` is constant
*bar = "bar";  // Valid because the string object itself is not constant

声明

const std::string const& bar

是多余的,因为它说 bar 是对常量 std :: string 的引用.

is redundant, as it says that bar is a reference to a constant std::string which is constant.

至于

std::string & bar const

那根本不是有效的语法,因为 cv限定符可以不要放在那儿.

That simply isn't valid syntax as a cv-qualifier can't be placed there.

这篇关于函数声明中以及其他位置的&符号右侧的C ++ const的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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