我的类(class)有 2 个构造函数:
Class()
Class(const std::string &fileName)
我不想在构造函数的其他地方设置我的文件名。 但是构造函数调用取决于运行时:
int main(int ac, char**av)
{
if (ac > 1)
Class test(av[1])
else
Class test;
return (0);
}
此表示法无法编译,因为“类未在范围内定义”
另一种解决方案是使用类指针:
int main(int ac, char **av)
{
Class *test;
if (ac > 1)
test = new Class(av[1]);
else
test = new Class();
/* Do stuff ...*/
delete test;
return (0);
}
但我不喜欢使用新的。 还有别的办法吗?
提前致谢:)
最佳答案
你可以这样做:
Class make_class(int ac, char**av)
{
if (ac > 1) {
return Class(av[1]);
} else {
return Class();
}
}
int main(int ac, char**av)
{
Class test = make_class(ac, av);
return (0);
}
关于c++ - 在运行时使用不同的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21852913/