具有私有构造函数的类的全局对象

发布于 2025-01-04 23:56:17 字数 230 浏览 4 评论 0原文

是否有可能以某种方式将全局范围声明为类的友元?

我面临的问题如下:

class Foo
{
    Foo() {}
};

Foo foo; //error: 'Foo::Foo()' is private

所以,我想要的是能够在全局范围内声明一个 Foo 对象,而不是在其他任何地方。

请注意,这个问题纯粹是出于兴趣,我并不是想解决实际问题。

Is it possible to somehow declare the global scope as a friend of a class?

The problem I am facing is the following:

class Foo
{
    Foo() {}
};

Foo foo; //error: 'Foo::Foo()' is private

So, what I want is to be able to declare an object of Foo at the global scope but not anywhere else.

Note that this question is purely out of interest, I'm not trying to solve an actual problem.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

何时共饮酒 2025-01-11 23:56:17

不,这是不可能的。您只能将特定的类或函数命名为友元。不可能使包含全局命名空间的命名空间成为友元。

我认为没有一个好的解决方法的原因是,当您定义一个类或函数时,只允许一个定义(不考虑重载,它们实际上是不同的函数)。但是,您可以根据需要多次打开名称空间,并每次都向其中添加额外的内容。因此,如果您允许访问特定名称空间,任何想要的人都可以输入:

namespace TheNamesapceWithAccess
{
  // I've got access to it here too as well as
  // to the original namespace definition that was
  // the only one that was intended to be allowed access.
  // And I could define a function here that allows access the private thing
  // from outside this namespace. I've just subverted the access restriction
  // you intended.
}

No, it's not possible to do that. You can only name specific classes or functions as friends. It's not possible to make a namespace including the global namespace a friend.

I think the reason there isn't a good work around is that when you define a class or function, only one definition is allowed (not considering overloads, which are really different functions). But, you are allowed to open a namespace as many times as you want and append extra stuff into it each time. So, if you allowed access to a particular namespace, anybody who wanted to could type:

namespace TheNamesapceWithAccess
{
  // I've got access to it here too as well as
  // to the original namespace definition that was
  // the only one that was intended to be allowed access.
  // And I could define a function here that allows access the private thing
  // from outside this namespace. I've just subverted the access restriction
  // you intended.
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文