函数 return 可以在 Processing 中自定义类型吗?
Can functions return user-defined types in Processing?
我写了一个class来表示Processing中的复数(我称之为Complex
)。我想在复数上实现基本的算术函数。但是,如果我将方法的 return 类型声明为 Complex
并尝试 return 一个新对象,我会收到一条错误消息,上面写着
“无效方法不能 return 一个值”。我还收到函数名称后的括号错误,以及分隔 x
和 y
参数的逗号。
但是,我注意到如果我将 return 类型更改为内置值(例如 int
或 String
)和 return 某个任意值正确的类型,所有这些错误都会消失。我也没有看到函数 returning 非内置类型的任何示例。这两个事实使我相信我可能无法 return 我定义的 class 对象。所以我的问题是是否可以 return 来自我在处理中定义的 class 的对象。如果没有,有什么解决办法吗?
这是我的代码:
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 就像使用 java 一样,您可以 return 任何具有函数的对象类型。这是一个简短的概念证明,供您复制、粘贴和尝试:
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
方法亮起,好像它正在遮蔽另一个方法,但它并没有阻止它按预期 运行。
如果情况仍然存在,您可能需要 post 更多代码,因为问题可能出在意想不到的地方。祝你好运!
我写了一个class来表示Processing中的复数(我称之为Complex
)。我想在复数上实现基本的算术函数。但是,如果我将方法的 return 类型声明为 Complex
并尝试 return 一个新对象,我会收到一条错误消息,上面写着
“无效方法不能 return 一个值”。我还收到函数名称后的括号错误,以及分隔 x
和 y
参数的逗号。
但是,我注意到如果我将 return 类型更改为内置值(例如 int
或 String
)和 return 某个任意值正确的类型,所有这些错误都会消失。我也没有看到函数 returning 非内置类型的任何示例。这两个事实使我相信我可能无法 return 我定义的 class 对象。所以我的问题是是否可以 return 来自我在处理中定义的 class 的对象。如果没有,有什么解决办法吗?
这是我的代码:
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 就像使用 java 一样,您可以 return 任何具有函数的对象类型。这是一个简短的概念证明,供您复制、粘贴和尝试:
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
方法亮起,好像它正在遮蔽另一个方法,但它并没有阻止它按预期 运行。
如果情况仍然存在,您可能需要 post 更多代码,因为问题可能出在意想不到的地方。祝你好运!