【问题标题】:Problems with constructor of a class with template带有模板的类的构造函数的问题
【发布时间】:2013-09-25 00:42:39
【问题描述】:

我正在尝试使用 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

老实说,我不知道会发生什么。将非常感谢任何可以为我指明正确方向的人...

【问题讨论】:

  • 你不应该留下警告......如果只是因为它们混淆了编译器的输出
  • 好像用的是你自己的vector。这是故意的,还是您的意思是使用std::vector?显示您在vector.h 中定义的vector 类的构造函数。
  • 粘贴整个错误信息。我不在乎它有多长或者你认为什么不重要。您所显示的只是 location 信息,但实际的 error 仍未在发布的消息中。
  • 抱歉问了些傻事,但你只是展示了诱人的 sn-ps 代码,所以我必须问:vector 构造函数是公开的吗?
  • 你不应该允许为你的代码发出警告。直到您达到 800 级技能并培养了至少三个学徒。

标签: c++ class templates constructor containers


【解决方案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 ****

【讨论】:

  • 注意:我从不坚持没有错误。我坚持说你没有张贴。我仍然坚持说你错过了粘贴它。老实说,我没有看到只有警告的结果。
  • 好吧,至少你坚持要我发布错误,所以我注意到没有错误。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-22
  • 1970-01-01
  • 1970-01-01
  • 2015-08-04
  • 2015-06-17
相关资源
最近更新 更多