什么是 C++相当于 C# 的 readonly 字段修饰符?
锁定状态很棒。在 C# 中,您可以通过将字段声明为只读来确保构造函数完成后字段不会更改其值/引用。
class Foo
{
private readonly string _foo;
public Foo() {
_foo = "Unchangeable";
}
public void ChangeIt() {
_foo = "Darn"; // compiler error
}
}
我可以用 C++ 做同样的事情吗?如果是这样,怎么办?如果没有,为什么不呢?
Locking down state is great. In C# you can ensure that a field doesn't change it's value/reference once the constructor completes by declaring it as readonly
.
class Foo
{
private readonly string _foo;
public Foo() {
_foo = "Unchangeable";
}
public void ChangeIt() {
_foo = "Darn"; // compiler error
}
}
Can I do the same thing with C++? If so, how? If not, why not?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
那将是 const。请注意,此关键字在不同的上下文中表示不同的含义。
That would be const. Note that this keyword means a couple of different things in different contexts.
直接没有这样的事情。您可以将私有字段与公共 getter(但没有 setter)一起使用。但这仅适用于调用您的代码的其他类。
Foo
始终对其成员拥有完全访问权限。但由于您是Foo
的实现者,所以这不是真正的问题。There is no such thing directly. You can use a private field with a public getter (but no setter). But that would only apply to other classes calling your code.
Foo
always has full acces to its members. But since you are the implementer ofFoo
, this is no real problem.在阅读了已接受的答案后,我并不清楚要完全等同于
readonly
关键字,您需要像这样声明成员:希望这会有所帮助。
It was not immediately clear to me after reading the accepted answer that to make exact equivalent of
readonly
keyword you need to declare the member like this:Hope this helps.
C++ 中的引用不可重新绑定,因此它相当于 C# 只读引用。
A reference in C++ is not rebindable, so it's equivalent to a C# readonly reference.
C++ 有
const
,它的作用与 C# 中的readonly
相同。C++ has
const
, which does the same job asreadonly
in C#.在进行从 C# 到 C++ 的转录时,我有与您相同的需求
这只是一个语法错误,因为该指令存在于 C++ (Visual C++)
语法中: [readonly]
“只读 C++ 属性与只读 MIDL 属性具有相同的功能。
如果要禁止修改方法参数,请使用 in 属性。”
来源:https://msdn.microsoft.com/en-us/library/45x4ky7s.aspx
来源:https://msdn.microsoft.com/library/windows/desktop/aa367152
I had the same need as you when doing a transcription from C# to C++
and it is just a syntax error because this instruction exists in C++ ( visual C++)
Syntax : [readonly]
"The readonly C++ attribute has the same functionality as the readonly MIDL attribute.
If you want to prohibit modification of a method parameter, then use the in attribute."
source : https://msdn.microsoft.com/en-us/library/45x4ky7s.aspx
source : https://msdn.microsoft.com/library/windows/desktop/aa367152