Mar*_*per 7 c++ arrays operator-overloading multidimensional-array
我有一个带有多维数组的类:
可以使用此类创建一个,两个,......,n维数组
如果数组有n个维度,我想用n operator[]来获取一个对象:
例:
A a({2,2,2,2}];
a[0][1][1][0] = 5;
Run Code Online (Sandbox Code Playgroud)
但数组不是指针的向量,导致其他向量等...
所以我希望operator []返回一个类对象,直到最后一个维度,然后返回一个整数
这是一个强烈简化的代码,但它显示了我的问题:
我收到的错误: "[Error] cannot convert 'A::B' to 'int' in initialization"
#include <cstddef> // nullptr_t, ptrdiff_t, size_t
#include <iostream> // cin, cout...
class A {
private:
static int* a;
public:
static int dimensions;
A(int i=0) {
dimensions = i;
a = new int[5];
for(int j=0; j<5; j++) a[j]=j;
};
class B{
public:
B operator[](std::ptrdiff_t);
};
class C: public B{
public:
int& operator[](std::ptrdiff_t);
};
B operator[](std::ptrdiff_t);
};
//int A::count = 0;
A::B A::operator[] (std::ptrdiff_t i) {
B res;
if (dimensions <= 1){
res = C();
}
else{
res = B();
}
dimensions--;
return res;
}
A::B A::B::operator[] (std::ptrdiff_t i){
B res;
if (dimensions <=1){
res = B();
}
else{
res = C();
}
dimensions--;
return res;
}
int& A::C::operator[](std::ptrdiff_t i){
return *(a+i);
}
int main(){
A* obj = new A(5);
int res = obj[1][1][1][1][1];
std::cout<< res << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
operator[]在 中从左到右计算,obj[1][1]...[1]因此obj[1]返回一个B对象。假设现在您只有int res = obj[1],那么您将分配给一个B对象(或C在多次调用 的情况下为对象[])int,但没有从B或C到 的转换int。您可能需要编写一个转换运算符,例如
operator int()
{
// convert to int here
}
Run Code Online (Sandbox Code Playgroud)
for A、Band C、 作为重载运算符不会被继承。
A我只是通过为and编写这样的运算符就摆脱了编译错误B(当然,由于存在未定义的函数,我有链接错误)。
另请注意,如果您想编写类似的内容obj[1][1]...[1] = 10,则需要重载operator=,因为同样没有从int到A或您的代理对象的隐式转换。
希望这是有道理的。
PS:另请参阅@Oncaphillis 的评论!
| 归档时间: |
|
| 查看次数: |
1064 次 |
| 最近记录: |