我明白,一旦留下该代码块,在 switch case 或 if 条件内部实例化的对象将不再存在(如 this question 中所述)。但是,实例化对象的正确方法是什么,具体取决于例如用户输入?我相信人们可以从这个例子中看出我正在(笨拙地)尝试做什么:
class triangle
{
public:
static const int dimension = 2;
};
class tetrahedron
{
public:
static const int dimension = 3;
};
template<class T>
class element
{
public:
int getDimension()
{
return T::dimension;
}
};
int main()
{
int elementType;
std::cout<< "Enter 1 for triangle or 2 for tet: "
std::cin >> elementType;
switch(elementType)
{
case 1:
{
element<triangle> myElementFile;
break;
}
case 2:
{
element<tetrahedron> myElementFile;
break;
}
}
// I want to use myElementFile further, but it does not exist here
std::cout<< "The dimension is: " << myElementFile.getDimension(); //this won't work
return 0;
}
我不知道使用类作为“容器”来存储有关不同元素的信息然后将它们输入不同的类的总体方法是否是最佳的,但我现在应该坚持它,因为我被告知到。 :) 总的来说,我对 C++ 和 OOP 很陌生。感谢您的任何提示!
最佳答案
总体解决方案是分解您的代码。
template <typename T>
void process_thing(T const & t)
{
std::cout << "The dimension is: " << t.getDimension() << "\n";
}
int main()
{
switch (condition)
{
case Triangle:
{
process_thing(element<triangle>());
break;
}
case Tetrahedron:
{
process_thing(element<tetrahedron>());
break;
}
default:
{
// ...
}
};
}
不要在一个函数中完成所有事情,而是将功能组件分成不同的代码片段并按逻辑组合它们。
关于c++ - 重新审视 switch 内部的对象实例化 (c++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24814391/