首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >哪些语言(如果有的话)可以覆盖基元类型的+运算符?

哪些语言(如果有的话)可以覆盖基元类型的+运算符?
EN

Stack Overflow用户
提问于 2016-08-12 09:35:28
回答 2查看 45关注 0票数 1

正在和一些朋友讨论这个问题是否符合笔迹,这是基于大脑测试的。它将引导我们讨论是否可以对任何语言中的原语类型重载+-

是否有任何语言可以对以下内容进行评估:

代码语言:javascript
复制
answer = 8 + 11;
if (answer == 96){
    //Yay! It worked!
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-08-12 09:46:29

C#实现;不完全是您想要的(Trick不是原始类型),而是具有所需的行为:

代码语言:javascript
复制
  public struct Trick {
    public override bool Equals(object obj) {
      return true;
    }

    public override int GetHashCode() {
      return 0;
    }

    // Trick can be implicitly created from any int (e.g. from 19, 96 etc.)
    public static implicit operator Trick(int value) {
      return new Trick();
    } 

    // All Trick instances are equal to each other
    public static bool operator == (Trick left, Trick right) {
      return true;
    }

    public static bool operator != (Trick left, Trick right) {
      return false;
    }
  }

现在,我们准备测试Trick

代码语言:javascript
复制
  Trick answer;

  // ------ Now goes your fragment -----------------------

  answer = 8 + 11; // Trick instance can be implicitly created from int (from 19)

  // .Net can't compare answer (which is Trick) and int (96), however
  // Trick instance can be implicitly created from int (from 96) 
  // so .Net will create Trick instance from 96 and compare two Tricks
  if (answer == 96) { 
    // when comparing two Trick instances:
    // one created from 19 and other created from 96 
    // they are equal to one another
    Console.Write("Yay! It worked!");
  } 

你会得到

“耶!成功了!”

票数 1
EN

Stack Overflow用户

发布于 2016-08-12 11:45:45

C++和红宝石。

代码语言:javascript
复制
//C++    
class X
    {
     public:
      X& operator+=(const X& rhs) // compound assignment (does not need to be a member,
      {                           // but often is, to modify the private members)
        /* addition of rhs to *this takes place here */
        return *this; // return the result by reference
      }

      // friends defined inside class body are inline and are hidden from non-ADL lookup
      friend X operator+(X lhs,        // passing lhs by value helps optimize chained a+b+c
                         const X& rhs) // otherwise, both parameters may be const references
      {
        lhs += rhs; // reuse compound assignment
        return lhs; // return the result by value (uses move constructor)
      }
    };

红宝石:

代码语言:javascript
复制
class String
  def <<(value)
    self.replace(value + self)
  end
end

str = "Hello, "
str << "World."
puts str
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38914682

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档