【发布时间】:2014-07-17 22:12:07
【问题描述】:
我不明白一旦离开该代码块(如this question 中所述),在 switch case 或 if 条件内实例化的对象将不复存在。但是,根据例如,实例化对象的正确方法是什么?用户输入?我相信人们可以从这个例子中看出我(笨拙地)想要做什么:
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 的新手。感谢您的任何提示!
【问题讨论】:
标签: c++ class templates switch-statement