簡體   English   中英

c++ - 如何從模板基類的構造函數調用模板超類的構造函數?

[英]How to call a template super class's constructor from a template base class's constructor in c++?

我正在使用 sublimetext3 在 C++ 中編程。 我的程序有一個名為 Array 的超類和一個名為 IntArray 的子類。 這兩個類都是模板類。 目前,我在編譯程序時遇到問題。 它一直在我的 IntArray.cpp 文件中給我一個錯誤,特別是在我的基類的構造函數中,我用基類的構造函數的參數調用和初始化超類的構造函數。 我不確定如何從子類的模板構造函數調用超類的模板構造函數。 錯誤消息如下所示。 此外,錯誤消息下方是我的 main.cpp、Array.cpp、Array.h、IntArray.cpp、IntArray.h 和 Makefile 的源代碼文件。 該計划尚未完成。 我目前只有一種獲取數組大小的方法。

來自終端的錯誤消息:

IntArray.cpp:4:56: error: member initializer 'Array' does not name a non-static data member or base class
template<class T> IntArray<T>::IntArray(T s) throw() : Array(s) {
                                                       ^~~~~~~~

1 error generated.

主程序

#include <iostream>
#include <string>
#include "Array.h"
#include "IntArray.h"

int main(int argc, char** argv) {

  // make an array of doubles with size 10
  Array<int> iA(10);

  // get the size of the array
  std::cout<< "The size of IntArray is" <<iA.getSize()<<std::endl;

} // end of main

數組.cpp

#include "Array.h"

// constructor
template<class T> Array<T>::Array(T s) throw() {
  size = s;
}

// destructor
template<class T> Array<T>::~Array() throw() {

}

// getter methods
template<class T> T Array<T>::getSize() const throw() {
  return size;
}

數組.h

#ifndef ARRAY_H
#define ARRAY_H

template<class T> class Array {
private:
  T size;

public:
  Array(T s) throw();
  virtual ~Array() throw();
  // getter methods that throws an exception if the index is out of bounds
  T getSize() const throw();


  // setters that throws an exception if the index is out of bounds
};

#endif

IntArray.cpp

#include "IntArray.h"

// constructor
template<class T> IntArray<T>::IntArray(T s) throw() : Array(s) {

}

// desctructor
template<class T> IntArray<T>::~IntArray() throw() {

}

數組.h

#ifndef INTARRAY_H
#define INTARRAY_H
#include "Array.h"

template<class T> class IntArray : public Array<T> {

public:
  IntArray(T s) throw();
  virtual ~IntArray() throw();
  //int getSize() const throw();
};

#endif

生成文件

all:main

main.o: main.cpp Array.h IntArray.h
  g++ -c -Werror main.cpp

Array.o: Array.cpp Array.h
  g++ -c -Werror Array.cpp

IntArray.o: IntArray.cpp IntArray.h
  g++ -c -Werror IntArray.cpp

main: main.o Array.o IntArray.o
  g++ -o main main.o Array.o IntArray.o

template <class T> IntArray<T>::IntArray(T s) throw() : Array<T>(s) {}
                                                        //   ^^^ Use <T>

更重要的是,將實現也放在 .h 文件中。

請參閱為什么模板只能在頭文件中實現? .

我注意到的其他問題

  • 您使用T s表示大小是沒有意義的。 std::size_t s更有意義。
  • IntArray是一個類模板是沒有意義的。 對我來說使用更有意義:

     class IntArray : public Array<int> { ... };

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM