【问题标题】:Overloading the [] operator in Objective-C++ [duplicate]在Objective-C ++中重载[]运算符[重复]
【发布时间】:2012-09-10 12:13:08
【问题描述】:

可能重复:
Can I overload an operator in Objective-C?

在 Objective-C++ 中,是否可以重载消息传递运算符,即 []?可以和“.”一样吗?

【问题讨论】:

    标签: c++ objective-c operator-overloading objective-c++


    【解决方案1】:

    运算符重载只是 C++ 的一个特性,而不是 Objective-C 的特性。看问题: Can I overload an operator in Objective-C?

    根据我对 C++ 的了解(不知道它在 Objective-C++ 中的完全支持),您可以重载 [] 运算符,但不能重载 .运算符,您可以阅读here

    编辑(在 JefferyThomasty 的输入之后):Objective-C++ 不支持重载消息传递操作符。我给出的答案是正确的,但不适用于该运算符(仅适用于数组下标或 c++ 的其他“功能”)

    【讨论】:

    • user1107412 想要重载消息传递,而不是数组下标。
    • @JefferyThomas 这有什么区别,运营商的实际目的是什么? (我不这么认为。如果我错了,请纠正我!)
    • C++ 不支持[instance method:parameter] 重载。它不是 C++ 语法的一部分。这样想,您将需要id operator[](id instance, SEL method, ...) 的方法签名。它只是在 C++ 中不存在。
    【解决方案2】:

    这取决于你希望你的重载消息传递做什么。

    Objective C 中的消息传递是动态的,您可以在多个级别将代码插入到消息传递系统中。最简单的是Message Forwarding。除此之外,还有Dynamic Method Resolution 和使用来自runtimeclass_replaceMethod()

    Objective-C 属性的点运算符是消息传递的捷径。它的工作方式与调用 -prop-setProp: 获取和设置属性的消息传递类似。

    C 结构的点运算符不可重载。

    【讨论】:

      【解决方案3】:

      为了重载c++下标操作符,

      class MyClass {
      private: 
          int myList[10];
      public:
          int& operator [] (const int index) {return myList[index];} // Check for index out of bounds if necessary.
      };
      

      这是它通常的样子。 int& 用于返回引用,所以你可以写

      MyClass a;
      a[1] = 3;
      

      没有int&,你只能访问它,不能修改它。阅读更多here

      您不能在 Objective-C 中重载运算符。 关于您重载“。”的问题,您可以重载的运算符只有几个,即:

      +    -    *    /    =    <    >    +=   -=   *=   /=   <<   >>
      <<=  >>=  ==   !=   <=   >=   ++   --   %    &    ^    !    |
      ~    &=   ^=   |=   &&   ||   %=   []   ()   ,    ->*  ->   new 
      delete    new[]     delete[]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-10-27
        • 1970-01-01
        • 2012-12-22
        • 2016-09-26
        • 2012-04-21
        • 1970-01-01
        相关资源
        最近更新 更多