有一个私人类型的公共成员有什么意义吗?
考虑以下C ++代码,其中Member foo
具有私有类型:
class Object {
private:
struct MyPrivateThing {
long double Member;
};
using Type = MyPrivateThing;
public:
Type foo = {32.45L};
// MyPrivateThingFoo also works
};
int main() {
// Object::Type f = {34.567L}; ERROR: Object::Type is private
decltype(Object::foo) thingy = {945.67L}; // Fine
auto x = Object().foo;
return x.Member * thingy.Member;
}
尽管此代码是合法的C ++并编译了良好的,但似乎有点违反直觉 - Object ::类型
是私人的,在班级外不可访问,但是我们仍然可以通过使用auto
间接地参考它以获取该类型的变量。
看来,要做的更直接的事情就是让每个公共成员都有公共类型。
您能想到这种模式的任何有效的用例吗?
Consider the following C++ code, where member foo
has a private type:
class Object {
private:
struct MyPrivateThing {
long double Member;
};
using Type = MyPrivateThing;
public:
Type foo = {32.45L};
// MyPrivateThingFoo also works
};
int main() {
// Object::Type f = {34.567L}; ERROR: Object::Type is private
decltype(Object::foo) thingy = {945.67L}; // Fine
auto x = Object().foo;
return x.Member * thingy.Member;
}
Although this code is legal C++ and compiles fine, it seems a bit counter-intuitive —Object::Type
is private and not accessible outside the class, yet we can still indirectly refer to it by using auto
to get a variable of that type.
It would seem that the more straightforward thing to do would be to just make every public member have a public type.
Can you think of any valid use-cases for this pattern?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论