如何重载以使ob2[0][0] << 112.6
有效?目前我正在使用插入功能进行此操作。
template <class X>
class A
{
void insert(int row, int col, type val)
{
...
}
};
template <class Y>
class B
{
vector<int> row;
vector<vector<pair<int, Y> > > colval;
}
int main()
{
B<float> ob1;
A<B<float> > ob2;
ob2[0][0] << 112.6;
}
答案 0 :(得分:1)
使用代理对象:
class A
{
// provide operator << for a single row/column
struct cell_proxy
{
void operator<<(float value) const
{
target->insert(row, col, value);
}
A* target;
size_t row;
size_t col;
};
// provide access to elements of a single row
struct row_proxy
{
cell_proxy operator[](size_t col)
{
cell_proxy res = {target, row, col};
return res;
}
A* target;
size_t row;
};
row_proxy operator[](size_t row)
{
row_proxy res = {this, row};
return res;
}
};
也就是说,您可以使用运算符重载,代理和模板来获得快乐,但您也可以使代码不可更改且不可执行。我个人觉得insert()调用更具可读性。
答案 1 :(得分:0)
试试这个:
template < class E >
class B
{
vector < std::pair < int, E > inner;
public:
E& operator[] ( int i )
{
// resize inner if i is beyond current size
return ( inner [ i ].second );
}
};
template < E >
class A
{
vector < B < E > > outer;
public:
B < E >& operator[] ( int i )
{
// resize outer if i beyond current size
return ( outer [ i ] );
}
};
int main()
{
A < int > a;
a [ 2 ] [ 3 ] = 1;
return ( 0 );
}
边缘有点粗糙,但是......