Typedef学生不能正常工作

时间:2012-12-19 07:34:55

标签: c++ arrays templates typedef

我正在测试一个数组模板。它适用于字符串类型和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;   
 }

1 个答案:

答案 0 :(得分:4)

学生没有构造函数,你无法调用Student("123456789");尝试为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_;
};