[cpp] 关于返回内嵌类对象的成员函数
ling
xl-yc-lzj at necsoft.com.cn
Tue Oct 17 11:36:34 CST 2006
请教一个问题,下面代码中类Array2D的成员函数Array1D& operator[] (int index)
如果定义在类外面时(注释掉的代码),编译通不过,定义在类里面就没有问题,
不知道为什么。
编译错误:
E:\work\study\c&c++\src\m30.cpp:61: error: expected constructor, destructor,
or type conversion before "Array2D"
E:\work\study\c&c++\src\m30.cpp:61: error: expected `;' before "Array2D"
E:\work\study\c&c++\src\m30.cpp:67: error: expected init-declarator before
"Array2D"
E:\work\study\c&c++\src\m30.cpp:67: error: expected `;' before "Array2D"
#include <iostream>
using namespace std;
template<class T>
class Array2D {
public:
Array2D(int x, int y);
~Array2D();
class Array1D {
public:
Array1D(int x);
~Array1D() { delete [] value; }
T& operator[] (int index);
const T& operator[] (int index) const;
private:
T * value;
};
Array1D& operator[] (int index) { return array[index]; }
const Array1D& operator[] (int index) const { return array[index]; }
private:
Array1D * array;
int xx, yy;
};
template<class T>
Array2D<T>::Array1D::Array1D(int x) : value(new T[x])
{
}
template<class T>
T& Array2D<T>::Array1D::operator[](int index)
{
return value[index];
}
template<class T>
const T& Array2D<T>::Array1D::operator[](int index) const
{
return value[index];
}
template<class T>
Array2D<T>::Array2D(int x, int y) : xx(x), yy(y)
{
array = static_cast<Array1D*>(operator new(x * sizeof(Array1D)));
for (int i = 0; i < y; ++i) {
new(&array[i]) Array1D(y);
}
}
template<class T>
Array2D<T>::~Array2D()
{
for (int i = xx - 1; i >= 0; --i) {
array[i].~Array1D();
}
operator delete [](array);
}
/*template<class T>
Array1D Array2D<T>::operator[](int index)
{
return a.array[index];
}*/
/*template<class T>
const Array1D Array2D<T>::operator[] (int index) const
{
return array[index];
}*/
int main()
{
Array2D<int> a(10, 10);
a[1][1] = 1;
a[0][0] = 10;
cout << a[1][1] << endl;
cout << a[0][0] << endl;
}
More information about the Cpp
mailing list