c++ 类模板对象怎样分类实例化?
template<classnumtype>classStack{public:Stack(){numtypestack[100];n=0;}voidpush(){cou...
template <class numtype>
class Stack
{
public:
Stack()
{
numtype stack[100];
n = 0;
}
void push()
{
cout << "input the number you wanna push in:";
if (n == stack_max - 1)
cout << "failed beacuse the stack is full";
cin >> stack[++n];
}
void pop()
{
if (n <= 0)
{
cout << "the stack is empty";
}
cout << "the digital you want:";
cout << stack[--n];
}
private:
int n;
};
这样一个类模板,想通过选择来决定数据类型用int还是double,但是又不能在if语句中实例化对象有什么替代方法吗? 展开
class Stack
{
public:
Stack()
{
numtype stack[100];
n = 0;
}
void push()
{
cout << "input the number you wanna push in:";
if (n == stack_max - 1)
cout << "failed beacuse the stack is full";
cin >> stack[++n];
}
void pop()
{
if (n <= 0)
{
cout << "the stack is empty";
}
cout << "the digital you want:";
cout << stack[--n];
}
private:
int n;
};
这样一个类模板,想通过选择来决定数据类型用int还是double,但是又不能在if语句中实例化对象有什么替代方法吗? 展开
4个回答
展开全部
#include <iostream>
using namespace std;
class StackBase
{
public:
virtual ~StackBase() {}
virtual void push() = 0;
virtual void pop() = 0;
};
class StackWrapper : public StackBase
{
StackBase* impl_;
public:
~StackWrapper() { if (impl_) delete impl_; }
StackWrapper() : impl_(0) {}
void push();
void pop()
{
if (impl_)
impl_->pop();
else
cout << "the stack is empty";
}
};
template <class numtype>
class Stack : public StackBase
{
friend class StackWrapper;
enum { stack_max = 100 };
numtype stack[stack_max];
void pushNum(numtype x)
{
stack[++n] = x;
}
public:
Stack()
{
n = 0;
}
void push()
{
if (n == stack_max - 1)
{
cout << "failed beacuse the stack is full";
return;
}
cout << "input the number you wanna push in:";
cin >> stack[++n];
}
void pop()
{
if (n <= 0)
{
cout << "the stack is empty";
return;
}
cout << "the digital you want:";
cout << stack[n--] << endl;
}
private:
int n;
};
void StackWrapper::push()
{
if (impl_)
impl_->push();
else
{
int x;
double y, t;
cout << "input the number you wanna push in:";
cin >> y;
x = y;
t = y - x;
if (t < 0) t = -t;
if (t < 1e-8) //int
{
Stack<int>* r = new Stack<int>();
cout << "Stack<int> created." << endl;
impl_ = r;
r->pushNum(x);
}
else
{
Stack<double>* r = new Stack<double>();
cout << "Stack<double> created." << endl;
impl_ = r;
r->pushNum(y);
}
}
}
int main()
{
StackWrapper s;
s.push();
s.push();
s.push();
s.pop();
s.pop();
return 0;
}
你想以第一个输入的数字来决定吗……如果第一个是int第二个是double会死喔
勉强写了一下,看到问题第一个想到的是这样做
展开全部
用swtich也行
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
楼主能说得再具体点吗?
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
怎么选择?条件是什么?
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询