c++ 类模板对象怎样分类实例化?
发布网友
发布时间:2023-07-20 15:25
我来回答
共4个回答
热心网友
时间:2024-12-04 11:29
#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会死喔
勉强写了一下,看到问题第一个想到的是这样做
热心网友
时间:2024-12-04 11:29
用swtich也行
热心网友
时间:2024-12-04 11:30
楼主能说得再具体点吗?
热心网友
时间:2024-12-04 11:31
怎么选择?条件是什么?