本文介绍了重载[] []的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述




我有一个包含二维数组的类。我需要

重载类似[] []运算符的东西,以便我能够通过类对象访问

内部数组元素。例如:


矩阵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




这篇关于重载[] []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 23:37