[英]C++: Assign value to global class variable
Consider the class MyClass
that has no default constructor. 考虑没有默认构造函数的类
MyClass
。
I want to write a code that looks like the following: 我想编写一个如下所示的代码:
MyClass instance;
void init_system() {
instance = MyClass(parameters, of, the, constructor);
}
The code I wrote above of course fails with the error MyClass has no C'tor that takes no arguments. 我上面写的代码当然失败了,错误MyClass没有没有参数的C'tor。
Is there any correct way to do it, or I must implement a workaround, eg using shared pointers? 有没有正确的方法,或者我必须实现一个解决方法,例如使用共享指针?
Well, either a default object of your class can sensibly exist, or it cannot. 好吧,你的班级的默认对象可以明智地存在,或者它不能。
In the latter case, you might be interested in std::optional
( boost::optional
before C++17) to defer the construction of the object. 在后一种情况下,您可能对
std::optional
(在C ++ 17之前的boost::optional
)感兴趣,以推迟对象的构造。
You could move the initialization of the object into your init_system()
function: 您可以将对象的初始化移动到
init_system()
函数中:
MyClass& init_system()
{
static MyClass instance(parameters, of, the, constructor);
return instance;
}
You may want to look up the singleton pattern, too, and read the extensive discussions about it ;) 您也可以查看单例模式,并阅读有关它的广泛讨论;)
And yes, another solution could be to use a unique_ptr<>
or shared_ptr<>
. 是的,另一种解决方案可能是使用
unique_ptr<>
或shared_ptr<>
。
There are 2 ways of achieving this.... 有两种方法可以实现这一目标....
MyClass instance(parameters, of, the, constructor);
Would initialize MyClass with the correct parameters. 将使用正确的参数初始化MyClass。
A singleton pattern 单身模式
MyClass & MyClass::getInstance(){
static MyClass instance( parameters, of, constructor );
return instance;
}
with getInstance returned at the time of calling. 在调用时返回getInstance。
The second pattern improves control over when the object is constructed. 第二种模式改进了对构造对象的控制。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.