在C ++中模拟C#索引器 [英] Simulating C# indexer in C++

查看:110
本文介绍了在C ++中模拟C#索引器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如您所知,在C#类中,我们可以定义一个具有多个参数的索引器。
但是在C ++中,operator []可以接受一个参数。有没有办法在C ++中使用多个参数来编写索引器?

As you know in C# classes we can define an indexr with more than one argument. But in C++ operator [ ] can accept one argument. Is there a way to wrtie an indexer in C++ with more than one argument?

C#中的索引器:

public AnyType this[arg1 , arg2 , .....]
{
    get { ... };
    set { ... };
}

[] C ++运算符:

[ ] operator in C++ :

AnyType & operator [] ( arg )
{
   // our code  
}


推荐答案

您可以返回一个临时的,它包含第一个索引并具有数据源的引用。

You can return a temporary, which holds the first index and has a reference the data source.

private:
    class BoundArg {
    private:
        Data& data;
        size_t i; 
    public:
        BoundArg (etc.)

        value_type& operator [] ( size_t j ) {
           return data.get ( i, j );
        }
    };

public:
value_type& get ( size_t i, size_t j ) ...

BoundArg operator [] ( size_t i )
{
   return BoundArg ( *this, i );
}

除非你已经存储了二维数组,否则它通常不值得复杂作为一维数组,在这种情况下临时只是指向数组中某处的指针。

Usually it's not worth the complexity, unless you've got a 2D array stored as a 1D array, in which case the temporary is just a pointer to somewhere into the array.

public:
value_type& get ( size_t i, size_t j ) { 
   return data_ [ i * rowWidth_ + j ];
}

value_type* operator [] ( size_t i )
{
   return data_ + i * rowWidth_;
}

这篇关于在C ++中模拟C#索引器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆