我正在学习用 Java 创建类,但遇到了奇怪的行为。
我想创建一个名为 My_class
的类,它有一个名为 add
的方法。该方法应采用 My_class
的成员并将其添加到括号中指定的 My_class
的另一个成员。
例如,运行这个:
My_class first = new My_class(2);
My_class second = new My_class(6);
My_class answer = first.add(second);
System.out.println(answer);
应该打印:
8
这是我为 My_class
使用的代码,但我一直遇到有关 My_class
如何处理 +
运算符的问题。我认为既然 My_class
是从 int
继承的,那应该没有问题,但显然我在这里遗漏了一些基本的东西。
public class My_class {
/* Data members*/
private int integer;
/* Constructors */
public My_class(int i) {integer = i;}
/* Methods */
public My_class add(My_class new_integer) {
return integer + new_integer;
}
我得到的不是预期的结果:
The operator + is undefined for the argument type(s) int, My_class
在此先感谢您的帮助!
最佳答案
如错误消息所述,您正在尝试添加一个 int
(integer
) 和 My_class
(new_integer
)。你不能那样做。
如果您想使用 new_integer
中的 integer
字段,您必须显式访问它:
return integer + new_integer.integer;
// -------------------------^^^^^^^^
(可能最好将 new_integer
参数重命名为不暗示它是 int
的东西,因为它不是,它是 的一个实例My_class
.)
上面的方法返回int
,所以方法是:
public int add(My_class new_integer) {
// ----^^^
return integer + new_integer.integer;
}
如果要保留add
的My_class
返回值,需要创建一个My_class
实例:
public My_class add(My_class new_integer) {
return new My_class(integer + new_integer.integer);
// ----^^^^^^^^^^^^^-----------------------------^
}
旁注:我也强烈建议在访问类的实例成员时始终使用 this.
,因此:
return this.integer + new_integer.integer;
// ----^^^^^
这是一个风格问题(Java 编译器会在必要时推断出 this.
),但恕我直言,它提高了清晰度,因为 integer
本身可以是一个局部变量,一个类名(尽管希望不是),一个静态成员,...
旁注 2:虽然您可以在自己的代码中做任何您想做的事,但压倒性的约定(也是官方约定,PDF)是使用混合大小写,每个单词都以大写字母开头,所以 MyClass
而不是 My_class
。
关于Java + 运算符行为未按预期继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56914478/