【问题标题】:Can functions return user-defined types in Processing?函数可以在处理中返回用户定义的类型吗?
【发布时间】:2020-12-08 08:12:33
【问题描述】:

我写了一个类来表示处理中的复数(我称之为Complex)。我想对复数实现基本的算术函数。但是,如果我将方法的返回类型声明为 Complex 并尝试返回一个新对象,我会收到一个错误,上面写着 “无效方法不能返回值”。我还收到函数名称后面的括号错误,以及分隔 xy 参数的逗号。

但是,我注意到如果我将返回类型更改为内置的(例如intString)并返回正确类型的任意值,所有这些错误都会消失。我也没有看到任何返回非内置类型的函数示例。这两个事实使我相信我可能无法返回我定义的类的对象。所以我的问题是是否可以从我在处理中定义的类中返回一个对象。如果没有,有没有办法解决这个问题?

这是我的代码:

class Complex {
  int re, im; // real and imaginary components
  
  Complex(int re, int im) {
    this.re = re;
    this.im = im;
  }
}

Complex add(Complex x, Complex y) {
  int re_new = x.re + y.re;
  int im_new = x.im + y.im;
  return new Complex(re_new, im_new);
}

【问题讨论】:

    标签: processing


    【解决方案1】:

    使用 Processing 就像使用 java 一样,您可以使用函数返回任何对象类型。下面是一个简短的概念证明,供您复制、粘贴和尝试:

    void setup() {
      Complex a = new Complex(1, 5);
      Complex b = new Complex(2, 6);
    
      Complex c = add(a, b);
      println("[" + c.re + ", " + c.im + "]");
    }
    
    void draw() {
    }
    
    class Complex {
      int re, im; // real and imaginary components
    
      Complex(int re, int im) {
        this.re = re;
        this.im = im;
      }
    }
    
    Complex add(Complex x, Complex y) {
      int re_new = x.re + y.re;
      int im_new = x.im + y.im;
      return new Complex(re_new, im_new);
    }
    

    我注意到add 方法亮起,就好像它正在遮蔽另一个方法,但它并没有阻止它按预期运行。

    如果情况仍然存在,您可能需要发布更多代码,因为问题可能出乎意料。祝你好运!

    【讨论】:

    • 谢谢,这很有帮助!我发布的代码是我编写的所有代码(Complex 类中的 toString 方法除外)。我所做的到底有什么问题?我仔细检查了所有括号是否正确,以及其他语法错误,例如分号。我没有发现任何明显的错误。有什么想法吗?
    • 如果你评论draw() 方法,你会看到那个可怕的错误再次弹出。 Processing 喜欢它的 draw() 循环,你无法避免它,但如果你愿意,你可以避免使用它。不过我不建议这样做,因为一旦你习惯了它的工作方式,它就会是一个非常好的游戏循环。
    猜你喜欢
    • 2011-01-30
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 2021-07-28
    • 2015-05-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多