【发布时间】:2016-09-22 12:46:11
【问题描述】:
我已经实现了堆栈进程。这个程序应该与真正的堆栈内存完全相同。此外,我正在尝试使用模板并使程序更通用。我在使用#define DEFAULT_SIZE 10 作为类构造函数的参数时遇到了问题。
首先,当我将DEFAULT_SIZE 放入构造函数的原型中时,它会顺利进行:
#define DEFAULT_SIZE 10
template<typename T>
class stack {
public:
stack(int size=DEFAULT_SIZE);
private:
T *elements;
int size;
int count;
};
template<typename T>
stack<T>::stack(int s) {
cout << "--constructor called\n";
size = s;
elements = new T[size];
count = 0;
}
但是当我将DEFAULT_SIZE 放在类构造函数的大纲定义中时,我得到了这个错误:no appropriate default constructor available
#define DEFAULT_SIZE 10
template<typename T>
class stack {
public:
stack(int size);
private:
T *elements;
int size;
int count;
};
template<typename T>
stack<T>::stack(int s=DEFAULT_SIZE) {
cout << "--constructor called\n";
size = s;
elements = new T[size];
count = 0;
}
最后是程序的主体:
int main() {
stack<int> u;
u.push(4);
}
我的问题不是关于“为什么模板只能在头文件中实现?”我的问题是我使用DEFAULT_SIZE的地方。
【问题讨论】:
-
请使用代码标题修复您的代码块。
-
多谢提醒,问题清楚了吗?
-
这段代码中的“没有合适的默认构造函数可用”错误是从哪里得到的?
-
我在我写的行中得到错误 (stack
u;) -
Why can templates only be implemented in the header file?的可能重复基本上是把实现放在头文件中,而不是创建单独的实现文件。
标签: c++ class templates constructor default-arguments