【发布时间】:2015-11-04 17:06:12
【问题描述】:
在Dev C++ 下编译时,我得到passing 'const Array' as 'this' argument of 'int& Array::operator[](int)' discards qualifiers。如果我在cygwin 上使用gcc 进行编译,我会收到一些此类错误消息:
error: extra qualification ‘Array::’ on member ‘Array’ [-fpermissive]
你能告诉我错误的原因是什么吗?我在这段代码上花了很多时间,但仍然无法使其正常工作。
#include<iostream>
using namespace std;
class Array
{
int *m_ptr;
int m_size;
public:
Array(int sz)
{
cout<<"constructor\n";
m_size = sz;
m_ptr = new int[sz];
}
~Array()
{
cout<<"Delete\n";
delete[] m_ptr;
}
int& operator[] (int j)
{
cout<<"Operation []\n";
return m_ptr[j];
}
void Array::copy(const Array& ar)
{
m_size = ar.m_size;
m_ptr = new int[m_size];
int *ptr = ar.m_ptr;
int j;
for(j = 0;j < m_size; j++)
m_ptr[j] = ptr[j];
}
Array::Array(const Array& ar)
{
copy(ar);
}
void Array::print(const Array& ar)
{
int i;
int len = ar.m_size;
for(i = 0;i < len;i++)
cout<<ar[i]<<" ";
cout<<endl;
}
};
int main()
{
Array a1(10);
Array a2(5);
int i;
for(i = 0;i < 10;i++)
{
a1[i] = 1;
if(i < 5) a2[i] = 2;
}
print(a1);
return 0;
}
另外,我正在看的书也有这个功能
Array& operator= (const Array& ar)
{
delete m_ptr;
copy(ar);
return *this;
}
我不明白为什么我们需要使用这个功能。
【问题讨论】:
标签: c++ arrays dynamic-memory-allocation