尝试模拟向量时编译器错误C2106

时间:2010-09-09 23:58:26

标签: c++ arrays vector simulation

我正在尝试为我的类赋值写一个假向量,我目前在成员函数pushBack中遇到错误。 编译器似乎不喜欢递增保存“向量”中元素数量的SIZE变量。有什么我可能需要解决的吗? 我们非常感谢您的帮助,以及您可能遇到的任何其他问题。

/*
Write a simple program that simulates the behavior of vectors
-You should be able to add and remove elements to the vector
-You should be able to access an element directly.
-The vector should be able to hold any data type.
*/


#include <stdio.h>

template <class T, int SIZE>
class Vector
{
 #pragma region constructors&destructors
 private:
 T vec[SIZE];

 public:

 Vector()
 {}
 ~Vector()
 {}
 #pragma endregion

 template <class T/*, int SIZE*/>
 void defineVec(T var)
 {
  for(int i=0; i<SIZE; i++)
  {
   vec[i] = var;
  }
  //printf("All elements of the vector have been defined with %", var)
  //What should I do when trying to print a data type or variable 
                //of an unspecified one along with the '%'?
 }

 template <class T/*, int SIZE*/>
 void pushBack(T var)
 {
  SIZE ++; //C1205
  vec[SIZE - 1] = var;
 }

 template <class T/*, int SIZE*/>
 void popBack()
 {
  vec[SIZE - 1] = NULL;
  SIZE--;
 }

 //template <class T/*, int SIZE*/>
 void showElements()
 {
  for(int i=0; i<SIZE; i++)
  {
   printf("%d",vec[i]);
   printf("\n");
  }
 }
};

int main()
{
 Vector <int, 5> myints;
 myints.pushBack(6);
 myints.showElements();
 return 0;
}

1 个答案:

答案 0 :(得分:3)

您正在传递SIZE作为模板参数。在模板定义中,非类型模板参数基本上是常量 - 即,您无法修改它。

您需要定义一个单独的变量来跟踪当前正在使用的矢量相似的存储量。

相关问题