【问题标题】:Java + operator behavior not inherited as expectedJava + 运算符行为未按预期继承
【发布时间】:2019-07-06 13:21:16
【问题描述】:

我正在学习用 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 而不是 int 和一个对象。应该是return integer + new_integer.integer;
  • 您在问题中提到了plusadd。大概你的意思是add 在这两个地方?

标签: java class inheritance methods operator-keyword


【解决方案1】:

正如错误消息所述,您正在尝试添加int (integer) 和My_class (new_integer)。你不能那样做。

如果您想使用来自new_integerinteger 字段,您必须显式访问它:

return integer + new_integer.integer;
// -------------------------^^^^^^^^

(最好将new_integer 参数重命名为不暗示它是int 的名称,因为它不是My_class 的一个实例。)

上面返回int,所以方法是:

public int add(My_class new_integer) {
// ----^^^
    return integer + new_integer.integer;
}

如果要保持addMy_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.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-30
    • 1970-01-01
    • 1970-01-01
    • 2015-05-15
    • 2017-11-25
    • 1970-01-01
    • 2015-05-11
    • 2019-06-20
    相关资源
    最近更新 更多