我有一个非void类型参数C++类模板,如何在特定的stutry中重载[]运算符?
template <typename T, unsigned int n>
class Array
{
private:
T* value;
public:
Array()
{
this->value = new T[n];
}
~Array() {
delete [] this->value;
}
Array(const Array & arr){
this->value = new T[n];
int a = n;
int b = 0;
while(a != 0)
{
this->value[b] = arr.value[b];
b++;
a--;
}
}
Array& operator=(const Array& arr)
{
int a = n;
int b = 0;
while(a != 0)
{
this->value[b] = arr.value[b];
b++;
a--;
}
return *this;
}
T& operator[](int a)
{
return this->value[a];
}
unsigned int size()
{
return n;
}
};
以上是我的模板类以下是一个名为“test”类的类模板。
class Test
{
public:
Test() { std::cout << "Test::Test()" << std::endl; }
Test(Test const&) { std::cout << "Test::Test(Test const&)" << std::endl; }
~Test() { std::cout << "Test::~Test()" << std::endl; }
Test& operator=(Test const&)
{
std::cout << "Test& Test::operator=(Test const&)" << std::endl;
return *this;
}
void print() const { std::cout << "Test::print() const" << std::endl; }
void print() { std::cout << "Test::print()" << std::endl; }
};
而且在我的main.cpp文件,我写了这个
int main(int, char*[])
{
Array<Test, 3> arr_1;
arr_1[1].print();
Test& t1 = arr_1[2];
t1.print();
return 0;
}
我想要做的是,
当我打电话arr_1[1].print();
,
它使用print() const
从我的“测试”类
当我做功能
,并呼吁t1.print();
,
它使用print()
(非const函数)。
我不明白我怎么可以重载[]运算符 返回一个const值和非const值。
我失去了从我的类模板的方法? 或者我的重载[]运算符实现是错误的?
谢谢!
我必须做“试验”类中的测试。感谢您的评论! –
@NeilButterworth,这实际上是我们班的练习题。对不起,没有指定它! –
看来你想要一个表达式'arr_1 [i]'有时候会返回一个const引用,而有时会返回一个非const引用。我不明白这是怎么可能的 - 它怎么知道什么时候返回哪个?当数组中的值实际上是非常量时,为什么要'arr_1 [1] .print();'调用一个常量版本的print()'? –