2

我正在测试一个数组模板。它适用于字符串类型和 int,但不适用于 typedef Student。我试图弄清楚,但我找不到问题所在。我没有使用单独的编译,因为它只是一个测试。我正在使用 Dev-C++。您的帮助将不胜感激。代码如下:

#include <iostream>
#include <vector>

using namespace std;

template <typename T>
class Array
{
  public:
     Array(int initialSize);
     ~Array();
     T & operator[](int i);

  private:
      T * m_pData;
      int m_nSize;                
};

//Implementing member functions in the Array template
template <typename T>
Array <T>::Array(int initialSize)
{
   m_nSize = initialSize; 
   m_pData = new T [m_nSize];  
};

template <typename T>
T & Array <T>::operator[](int i)
{
   return  m_pData[i];
};

template <typename T>
Array <T>::~Array()
{
   delete[]  m_pData;
};


typedef struct Student{}students[0];

//test array class implementatition
int main()
{
  //creating an array of 20 integers, then assigning the value 50 at index 2

  Array <int> myArray (20);
  myArray[2] = 50;
  cout << myArray[2] <<endl;

  //creating an array of string of size 10, then assigning the string "Fred" at index 5
  //then display the string
  Array <string> nameArray (10);
  nameArray[5] = string("Fred");
  cout << nameArray[5] <<endl;


  //creating an array of Student of size 100, then assigning the value "123456789" at     index 4
  //then display the value at that index

  Array <Student> students (100);
  students[4] = Student("123456789");  //here is the problem!!!
  ///cout << students[4] <<endl;

  system ("pause");
   return 0;   
 }
4

1 回答 1

4

Student没有构造函数,不能调用Student("123456789");Try为Student定义构造函数:

struct Student
{
  Student(): age_(0), name_("") {}
  Student(int age): age_(age), name_("") {}
  Student(const std::string& name): name_(name){
  }
  int age_;
  std::string name_;
};
于 2012-12-19T07:41:56.727 回答