我正在编写一段代码,我希望根据条件使用不同的类构造函数.到目前为止,我已经使用if和else语句来构造对象,但实例然后被"捕获"在括号中,不能在代码中进一步使用.
这是代码中的样子:
if (my_boolean){
MyClass my_object(arg1); //calling a first constructor
}
else {
MyClass my_object(arg1,arg2); //calling another constructor
}
//more code using my_object
Run Code Online (Sandbox Code Playgroud)
static到目前为止,我尝试使用关键字但没有成功.是否存在有条件地使用不同构造函数而不必重新定义构造函数的常用方法?
尝试以下:)
MyClass my_object = my_boolean ? MyClass(arg1) : MyClass(arg1,arg2);
Run Code Online (Sandbox Code Playgroud)
考虑到即使该类没有默认构造函数,此代码也能正常工作.
这是一个示范性的例子
#include <iostream>
#include <cstdlib>
#include <ctime>
int main ()
{
struct Point
{
Point( int x ) : x( x ) {}
Point( int x, int y ) : x( x ), y( y ) {}
int x = 0;
int y = 0;
};
std::srand( ( unsigned )std::time( 0 ) );
Point p = std::rand() % 2 ? Point( 1 ) : Point( 1, 2 );
std::cout << "p.x = " << p.x << ", p.y = " << p.y << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我得到了以下输出
p.x = 1, p.y = 2
Run Code Online (Sandbox Code Playgroud)
你得到了什么输出?:)
如果要使用给定范围之外的变量,则必须在该范围之外声明它.
void foo()
{
MyClass my_object;
if (my_boolean){
my_object = MyClass(arg1); //calling a first constructor,
//then copy or move assignment
}
else {
my_object = MyClass(arg1,arg2); //calling another constructor,
//then copy or move assignment
}
//more code using my_object
}
//Can no longer access my_object
Run Code Online (Sandbox Code Playgroud)
如果你想这样做,我建议定义一个移动赋值运算符,如果默认值不适用于你的目的(或者没有默认的移动赋值运算符).
此外,my_object如果将if/ elseblocks和object构造移动到单独的函数,则使用的代码可能更清晰,然后执行以下操作:
MyClass my_object = make_object(my_boolean);
Run Code Online (Sandbox Code Playgroud)
或者,如果arg1并且arg2不是全球性的,
MyClass my_object = make_object(my_boolean, arg1, arg2);
Run Code Online (Sandbox Code Playgroud)
如果创建一个对象比你在这里询问的要复杂得多,你可能希望查看工厂模式.
您可以使用智能指针而不是直接实例:
std::unique_ptr<MyClass> my_object;
if (my_boolean) {
//calling a first constructor
my_object.reset(new MyClass(arg1));
}
else {
//calling another constructor
my_object.reset(new MyClass(arg1,arg2));
}
//more code using my_object
Run Code Online (Sandbox Code Playgroud)
与此处提出的一些其他解决方案相比,这也适用于更大的if() {} else if() {}序列或switch块.
如果您不能使用具有最新标准的编译器,您可以std::auto_ptr以完全相同的方式使用旧的.
"
static到目前为止,我尝试使用关键字但没有成功."
好的!一个static变量当然不是你想要的这里.