我有一堂课
public class A {
public String attr ="A attribute";
public void method() {
System.out.println(this+" , "+this.attr);
}
public String toString() {
return("Object A");
}
}
Run Code Online (Sandbox Code Playgroud)
还有另一个继承自它的类
public class B extends A{
public String attr = "B attribute";
public void method() {
super.method();
}
public String toString() {
return("Object B");
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,method()of B只是for method()的包装A。
当我运行以下代码
B b = new B();
b.method();
Run Code Online (Sandbox Code Playgroud)
我得到的意思Object B , A attribute是输出,this并this.attr访问了不同的内容。为什么会这样?
不应该 …
似乎当我将不同的整数直接传递给函数时,C++ 会为它们分配相同的地址,而不是将不同的地址分配给不同的值。这是设计使然,还是可以关闭的优化?有关说明,请参阅下面的代码。
#include <iostream>
const int *funct(const int &x) { return &x; }
int main() {
int a = 3, b = 4;
// different addresses
std::cout << funct(a) << std::endl;
std::cout << funct(b) << std::endl;
// same address
std::cout << funct(3) << std::endl;
std::cout << funct(4) << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
这个问题的更大背景是,我正在尝试构建一个指向整数的指针列表,我将逐一添加(类似于funct(3))。由于我无法修改方法定义(类似于funct's),我想存储每个参数的地址,但它们最终都具有相同的地址。