c++ - Typedef Student 不工作

标签 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;   
 }

最佳答案

Student没有构造函数,无法调用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_;
};

关于c++ - Typedef Student 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13947543/

相关文章:

c++ - 用 strncpy 替换 strcpy

php - foreach逻辑不重复html

c++ - 强制非专用模板实例化出现编译错误

c++ - 使用来自外部类的可变参数模板的 args 部分专门化可变参数模板内部类是否合法

c++ - 将结构的动态数组复制到另一个结构

android - 我可以在 Android 上的 JNI 库中使用 C++ 异常吗?

java - 智能卡 ATR 更改未反射(reflect)在代码中

python - 在 Python 中计算两个图像之间的绝对差之和的最快方法是什么?

php - 将 X 个数组主菜转换为单个变量

c++ - 在容器中存储模板化对象