我尝试使用C ++和模板编写容器类。但是,我有一个编译错误,我不明白......
变量elems
是私有向量,声明为:
private:
vector<DataType> elems;
矢量是一个自定义矢量。它的构造函数是:
vector::vector(int init_capacity) : vect_capacity(init_capacity), vect_size(0), vect_elems(NULL){
assert(init_capacity >= 0);
if (init_capacity > 0){
vect_elems = new Object[init_capacity];
}
}
构造函数如下所示:
template <class DataType>
bag<DataType>::bag(int init_capacity) : elems(init_capacity) {
}
此代码返回以下错误:
../src/vector.h: In instantiation of ‘vector<DataType>::vector(int) [with DataType = int]’:
../src/bag.h:33:60: required from ‘bag<DataType>::bag(int) [with DataType = int]’
../src/bag_test.cpp:6:17: required from here
老实说,我不知道可能会发生什么。非常感谢任何可以指引我朝着正确方向前进的人......
答案 0 :(得分:1)
抱歉这个非常愚蠢的问题。编译器确实确实抱怨这一点,但代码实际上是编译的。感谢@WhozCraig和@n.m坚持认为这不是错误,我注意到它实际上正在构建。谢谢!为了将来参考,我发布了整个消息:
**** Build of configuration Debug for project ADS ****
make all
Building file: ../src/bag_test.cpp
Invoking: GCC C++ Compiler
g++ -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/bag_test.d" -MT"src/bag_test.d" -o "src/bag_test.o" "../src/bag_test.cpp"
In file included from ../src/bag_test.cpp:2:0:
../src/bag.h:23:66: warning: friend declaration ‘std::ostream& operator<<(std::ostream&, const bag<DataType>&)’ declares a non-template function [-Wnon-template-friend]
../src/bag.h:23:66: note: (if this is not what you intended, make sure the function template has already been declared and add <> after the function name here)
In file included from ../src/bag.h:2:0,
from ../src/bag_test.cpp:2:
../src/vector.h: In instantiation of ‘vector<DataType>::vector(int) [with DataType = int]’:
../src/bag.h:34:53: required from ‘bag<DataType>::bag(int) [with DataType = int]’
../src/bag_test.cpp:6:17: required from here
../src/vector.h:100:6: warning: ‘vector<int>::vect_capacity’ will be initialized after [-Wreorder]
../src/vector.h:99:6: warning: ‘int vector<int>::vect_size’ [-Wreorder]
../src/vector.h:108:1: warning: when initialized here [-Wreorder]
Finished building: ../src/bag_test.cpp
Building target: ADS
Invoking: GCC C++ Linker
g++ -o "ADS" ./src/bag_test.o
Finished building target: ADS
**** Build Finished ****