【问题标题】:Compiler Error C2106 when trying to simulate a vector尝试模拟矢量时出现编译器错误 C2106
【发布时间】:2010-09-09 23:58:25
【问题描述】:

我正在尝试为我的班级作业编写一个假向量,但我目前在成员函数 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;
}

【问题讨论】:

  • 错误是 C1205 还是 C2106 还是两者都有?

标签: c++ arrays vector simulation


【解决方案1】:

您将 SIZE 作为模板参数传递。在模板的定义中,非类型模板参数基本上是一个常量——也就是说,你不能修改它。

您需要定义一个单独的变量来跟踪当前使用的矢量类存储空间的多少。

【讨论】:

  • 它还需要某种动态分配。如果这个编译,它会导致缓冲区溢出。
  • @Matthew:嗯,有点。它不是为了正确利用空间而编写的,但它确实分配空间,因此动态分配不是绝对必要的。
  • 我从来没有说过它没有分配空间。如果他想要一个可以任意执行次数的pushBack方法,动态分配是绝对必要的;这似乎是任务的要求。照原样,它很容易缓冲区溢出。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-06
  • 2020-09-30
  • 1970-01-01
  • 1970-01-01
  • 2022-01-16
  • 1970-01-01
  • 2013-03-04
相关资源
最近更新 更多