C++:给全局类变量赋值

3
考虑没有默认构造函数的类MyClass
我想编写如下代码:
MyClass instance;

void init_system() {
    instance = MyClass(parameters, of, the, constructor);
}

我上面编写的代码当然会失败,错误提示为MyClass没有不带参数的构造函数。

有正确的方法可以解决吗,或者我必须实现一个变通方法,例如使用共享指针?

我至少不清楚你想做什么。你想初始化什么?静态成员变量(也称为类变量)吗?只需创建一个静态的init方法?还是其他什么?请澄清。你想要单例模式吗?还是静态工厂方法? - hyde
3个回答

7

要么你的类存在一个合理的默认对象,要么就不存在。


在后一种情况下,你可能会对 std::optional(C++17 之前是 boost::optional)感兴趣,以延迟对象的构建。


1
您可以将对象的初始化移动到您的init_system()函数中:
MyClass& init_system()
{
   static MyClass instance(parameters, of, the, constructor);
   return instance;
}

你可能还想查找单例模式,并阅读有关它的广泛讨论 ;)
是的,另一个解决方案可以使用unique_ptr<>或shared_ptr<>。

1
有两种实现方式……
MyClass instance(parameters, of, the, constructor);

请使用正确的参数初始化 MyClass。

单例模式

MyClass & MyClass::getInstance(){
   static MyClass instance( parameters, of, constructor );
   return instance;
}

在调用时返回getInstance。

第二个模式可以更好地控制对象的构建时间。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接