我有以下场景:
public class A {
private int x = 5;
public void print()
{
System.out.println(x);
}
}
public class B extends A {
private int x = 10;
/*public void print()
{
System.out.println(x);
}*/
public static void main(String[] args) {
B b = new B();
b.print();
}
}
Run Code Online (Sandbox Code Playgroud)
在执行代码时,输出为:5.
如何通过父类方法访问子类(B)变量(x)?
这可以在不覆盖print()方法的情况下完成(即在B中取消注释)吗?
[这很重要,因为在重写时我们必须再次重写print()方法的整个代码]
EDITED
更多澄清: -
(感谢您的所有时间和帮助)
我试图在SPOJ上解决问题(http://www.spoj.com/problems/GSS1)并最终使用Segment Tree制作以下代码.代码工作得很好.但是在某些输入上,当它试图从堆栈中取消分配向量的内存时,它会在程序结束时给出一个分段错误.我已经花了很多时间,但我找不到任何错误.任何帮助将受到高度赞赏.
#include <iostream>
#include <cmath>
#include <vector>
using namespace std;
struct Node{
int bend;
int bsum;
int ebeg;
int esum;
int maxSum;
Node(): bend(0), bsum(0), ebeg(0), esum(0), maxSum(0){}
Node(const Node& other): bend(other.bend), bsum(other.bsum), ebeg(other.ebeg), esum(other.esum), maxSum(other.maxSum){}
~Node(){}
};
class SegmentTree{
int N;
vector<Node> M;
vector<int> A;
public:
SegmentTree(int N){
this -> N = N;
Node temp;
M.resize((1 << ((int)log(N)+2))+1, temp);
}
SegmentTree(const SegmentTree& other): N(other.N), M(other.M), A(other.A) {}
~SegmentTree(){
M.clear();
A.clear();
}
void put(int a){
A.push_back(a);
} …Run Code Online (Sandbox Code Playgroud)