我编写了一个程序,其中包含一个带有构造函数的类和使用couts和cins编写的析构函数。
该类包含一个run()函数,我将其用作菜单。从菜单中,我希望用户选择选项1.测试构造函数(从类中创建实例)和2.测试析构函数(退出菜单并在main的末尾破坏)。
这是我的困境。
在main()中为了让我使用run()函数,我必须创建类的实例。但是,我正在使用模板。即。 Class<classType> classTypeRun
。
为了让我创建一个能够使用run()的实例,我必须指定一个classType,这将调用我不想要的构造函数。我只希望在用户从菜单中选择构造函数时运行构造函数。
最有效的方法是什么?
我应该只为run()函数创建一个继承类吗?
答案 0 :(得分:1)
让run()
成为免费功能,如下所示:
template <class T>
class MyT
{
public:
MyT(const T& v) : val_(v) {}
const T& get() const {return val_;}
private:
T val_;
};
int run()
{
int opt;
cout << " 1) Create\n 2)Destroy\n";
cin >> opt;
cin.ignore();
return opt;
}
int main()
{
int opt = 0;
std::auto_ptr<MyT<int>> t;
do
{
// call the menu...
opt = run();
// if the user selected option 1, and we haven't
// already constructed our object, do so now.
// (Calls MyT<int>())
if(opt == 1 && !t.get())
t.reset(new MyT<int>(10));
// if the user selected option 2 and we have
// already constructed our object, delete it now
// (Calls ~MyT<int>())
if(opt == 2 && t.get())
t.reset(0);
}
while(2 != opt);
}