C ++是否与Python的__setitem__等效

时间:2009-10-04 08:18:08

标签: c++ python

正如标题所要求的那样,C ++是否具有类似于Python的 setitem getitem 的类?

基本上,它允许您执行以下操作。

MyClass anObject;

anObject[0] = 1;
anObject[1] = "foo";

5 个答案:

答案 0 :(得分:6)

基本上,你重载下标运算符(operator[]),它返回一个引用(所以它可以被读取和写入)

答案 1 :(得分:6)

你可以重载[]运算符,但它与单独的getitem / setitem方法对不完全相同,因为你没有指定不同的获取和设置处理。

但是你可以通过返回一个覆盖赋值运算符的临时对象来接近。

答案 2 :(得分:3)

有关{+ 3}}中带有下标运算符的C ++中可能(以及不可能)的可能性(以及不可能)的讨论很有趣。

答案 3 :(得分:1)

要扩展Earwicker帖子:

#include <string>
#include <iostream>

template <typename Type>
class Vector
{
public:
    template <typename Element>
    class ReferenceWrapper
    {
    public:
        explicit ReferenceWrapper(Element& elem)
         : elem_(elem)
        {
        }

        // Similar to Python's __getitem__.
        operator const Type&() const
        {
            return elem_;
        }

        // Similar to Python's __setitem__.
        ReferenceWrapper& operator=(const Type& rhs)
        {
            elem_ = rhs;
            return *this;
        }

        // Helper when Type is defined in another namespace.
        friend std::ostream& operator<<(std::ostream& os, const ReferenceWrapper& rhs)
        {
            return os << rhs.operator const Type&();
        }

    private:
        Element& elem_;
    };

    explicit Vector(size_t sz)
     : vec_(sz)
    {
    }

    ReferenceWrapper<const Type> operator[](size_t ix) const
    {
        return ReferenceWrapper<const Type>(vec_[ix]);
    }

    ReferenceWrapper<Type> operator[](size_t ix)
    {
        return ReferenceWrapper<Type>(vec_[ix]);
    }

private:
    std::vector<Type> vec_;
};

int main()
{
    Vector<std::string> v(10);
    std::cout << v[5] << "\n";

    v[5] = "42";
    std::cout << v[5] << "\n";
}

答案 4 :(得分:1)

它不可移植,但MSVC有__declspec(property),它也允许索引器:

struct Foo
{
   void SetFoo(int index, int value) { ... }
   int GetFoo(int index) { ... }

   __declspec(property(propget=GetFoo, propput=SetFoo)) int Foo[]; 
}
除此之外,Earwicker确实概述了便携式解决方案,但他说你会遇到很多问题。