【问题标题】:Why does this pointer point to "Horse cult" instead of "Horse horse"?为什么这个指针指向的是“Horse cult”而不是“Horse horse”?
【发布时间】:2018-07-17 05:04:22
【问题描述】:
1   public class Horse {
2      Horse same;
3      String jimmy;
4   
5      public Horse(String lee) {
6         jimmy = lee;
7      }
8   
9      public Horse same(Horse horse) {
10        if (same != null) {
11           Horse same = horse;
12           same.same = horse;
13           same = horse.same;
14        }
15        return same.same;
16     }
17  
18     public static void main(String[] args) {
19        Horse horse = new Horse("youve been");
20        Horse cult = new Horse("horsed");
21        cult.same = cult;
22        cult = cult.same(horse);
23        System.out.println(cult.jimmy);
24        System.out.println(horse.jimmy);
25     }
26  }

当 Java 解释器运行第 22 行时,为什么 cult.same(horse) 返回一个指向“Horse cult”的指针,而不是返回指向相同的“Horse horse”的指针。第 11 行)指向?

【问题讨论】:

  • Horse 类中有一个字段和一个方法,它们都称为same。我很惊讶您的代码甚至可以编译,但无论如何都不要这样做。
  • 这不是实际代码,它来自数据结构类中的讨论部分

标签: pointers scope pass-by-value


【解决方案1】:

由于变量 same 是在 if 语句中声明的,因此在 if 块之外无法访问它。因此在return 语句中,它会找到same 变量cult self。

【讨论】:

  • 我明白了!在python中,作用域只在处理函数时才涉及,我没有意识到if语句和while语句在Java中也有自己的作用域。非常感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2020-10-11
  • 2018-04-19
  • 1970-01-01
  • 2011-08-10
  • 2023-04-01
  • 2020-09-09
  • 1970-01-01
  • 2023-03-07
相关资源
最近更新 更多