据我了解,在Java中,所有的变量是引用。在java和c + +中的实例变量
在接下来的代码:
class Parent {
public int x = 12;
}
class Child extend Parent {
public int x = 42;
}
Parent p = new Parent();
System.out.println(p.x);
12
Child c = new Child();
System.out.println(c.x);
42
p = c; // be careful here!
System.out.println(p.x);
12
我认为没有切片在这里,因为我们谈论refernces。出于这个原因,我不明白为什么要打印"12"
。 p
是现在指向的c
面积,c.x
是42
同样是在接下来的代码发生在C++:
class Parent {
public:
void example() { cout << "Parent" << endl; }
};
class Child : public Parent {
public:
void example() { cout << "Child" << endl; }
};
Parent * p = new Parent();
p->example()
Parent
Child * c = new Child();
c->example()
Child
p = c; // be careful here!
p->example()
Parent
+1:但你是什么性质呢? – 2011-06-17 13:37:50