[英]Compiler Error C2106 when trying to simulate a vector
I'm trying to write a fake vector for my class assignment, and I currently get an error in the member function pushBack. 我正在尝试为我的类分配编写伪造的向量,并且当前在成员函数pushBack中出现错误。 The compiler doesn't seem to like incrementing the SIZE variable which holds the number of elements in the "vector". 编译器似乎不喜欢增加保存“向量”中元素数量的SIZE变量。 Is there something I might need to fix? 我可能需要修复一些东西吗? Your assistance would be highly appreciated for helping me with this, and any other problems you might happen to find. 感谢您为我提供的帮助以及您可能碰到的任何其他问题的帮助。
/*
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;
}
You're passing SIZE
as a template parameter. 您正在传递SIZE
作为模板参数。 Inside the definition of a template, a non-type template parameter is basically a constant -- ie, you can't modify it. 在模板的定义内,非类型模板参数基本上是一个常量-即,您无法对其进行修改。
You'll need to define a separate variable to keep track of how much of the storage in your vector-alike is currently being used. 您需要定义一个单独的变量,以跟踪当前类似载体中有多少存储空间正在使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.