问题描述
我有一个包含二维数组的类。我需要
重载类似[] []运算符的东西,以便我能够通过类对象访问
内部数组元素。例如:
矩阵a =新矩阵(10,10);
a [1] [1] = 6;
这可能吗?如何在c ++中使用
类来模拟二维数组?谢谢
-Andre
没有运算符[] [],只有运算符[]。你可以用代理类做你想要的b $ b想要的东西,比如这个
类代理
{
public:
double operator [](int j)const;
double& operator [](int j);
};
class Matrix
{
public :
const代理运算符[](int i)const;
代理运算符[](int i);
};
我希望你明白这个想法,你在你的Matrix对象上重载operator []到
返回另一个类(Proxy类),然后重载operator [] on
代理类返回一个Matrix元素。
john
没有运算符[] [],只有运算符[]。你可以用代理类来做你想要的东西,比如这个类代理
{
公共:
double operator [](int j )const;
double& operator [](int j);
};
类Matrix
公共:
const代理运算符[](int i)const;
代理运算符[](int i);
};
我希望你明白这个想法,你在Matrix对象上重载operator []以返回另一个class(Proxy类),然后在
代理类上重载operator []以返回Matrix元素。
john
没有运算符[] [],只有运算符[]。你可以用代理类来做你想要的东西,比如这个类代理
{
公共:
double operator [](int j )const;
double& operator [](int j);
};
类Matrix
公共:
const代理运算符[](int i)const;
代理运算符[](int i);
};
我希望你明白这个想法,你在Matrix对象上重载operator []以返回另一个class(Proxy类),然后在
代理类上重载operator []以返回Matrix元素。
john
Hi,
I have a class which contains a two-dimensional array. I need to
overload something like the [][] operator so that I''m able to access the
internal array elements via the class object. For example:
Matrix a = new Matrix(10,10);
a[1][1] = 6;
Is this possible? How can I simulate a two dimensional array using a
class in c++? Thanks
-Andre
There is no operator[][], there is only the operator[]. You can do what you
want with a proxy class, something like this
class Proxy
{
public:
double operator[](int j) const;
double& operator[](int j);
};
class Matrix
{
public:
const Proxy operator[](int i) const;
Proxy operator[](int i);
};
I hope you get the idea, you overload operator[] on your Matrix object to
return another class (the Proxy class), you then overload operator[] on the
proxy class to return a Matrix element.
john
There is no operator[][], there is only the operator[]. You can do what you
want with a proxy class, something like this
class Proxy
{
public:
double operator[](int j) const;
double& operator[](int j);
};
class Matrix
{
public:
const Proxy operator[](int i) const;
Proxy operator[](int i);
};
I hope you get the idea, you overload operator[] on your Matrix object to
return another class (the Proxy class), you then overload operator[] on the
proxy class to return a Matrix element.
john
There is no operator[][], there is only the operator[]. You can do what you
want with a proxy class, something like this
class Proxy
{
public:
double operator[](int j) const;
double& operator[](int j);
};
class Matrix
{
public:
const Proxy operator[](int i) const;
Proxy operator[](int i);
};
I hope you get the idea, you overload operator[] on your Matrix object to
return another class (the Proxy class), you then overload operator[] on the
proxy class to return a Matrix element.
john
这篇关于重载[] []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!