c++与java中子类中调用父类成员的方法

 1 java中:
 2 import java.util.Scanner;
 3 public class ClassTest{
 4    public static void main(String args[]){
 5       child ch=new child(2);
 6       parent p=ch;
 7       p.print();
 8       //p.print2();//调用错误,父类中没有改成员方法,该方法只属于子类!
 9    }
10 } 
11 
12 class parent{
13    int xx;
14    parent(int x){
15       xx=x;
16    }
17    void print(){
18       System.out.println("this is parent!");
19    }
20    int f(){
21       int n;
22       Scanner s=new Scanner(System.in);
23       n=s.nextInt();
24       return n;
25    }
26 }
27 
28 class child extends parent{
29    int xx;
30    void print(){
31       System.out.println("this is child!");
32       System.out.println("父类中的f()函数得到的值:" + super.f());//当然也可以通过super来区分子类与父类同名函数的方法
33       System.out.println("子类中的f()函数得到的值:" + f());
34    }
35    void print2(){
36       System.out.println("this is test!");
37    }
38    child(int x){
39       super(x);//调用父类的构造方法
40       xx=5;
41    }
42    int f(){
43       System.out.println("父类中的xx值:" + super.xx);//通过super.xxx可以区分子类与父类同名的变量
44       System.out.println("子类中的xx值:" + xx);
45       return 15;
46    }
47 }
 1 c++中:
 2 #include<iostream> 
 3 using namespace std;
 4 class parent
 5 {
 6 public:
 7    int p;
 8    parent(int x)
 9    {
10        p=x;
11    }
12    void print()
13    {
14       cout<<"this is parent" <<endl;
15    } 
16    int f()
17    {
18     return 11; 
19    } 
20 }; 
21 
22 class child : public parent
23 {
24 public:
25    int p; 
26    child(int x):parent(x)
27    {
28        p=15;
29    }
30    int f()
31    {
32       return 22;
33    } 
34    void print()
35    {
36        cout<<"this is child!" <<endl;
37        cout<<"父类中的 p 变量值:"<<parent::p<<endl;
38        cout<<"子类中的 p 变量值:"<<p<<endl; 
39        
40        cout<<"父类中的f()函数值:"<<parent::f()<<endl;
41        cout<<"子类中的f()函数值:"<<f()<<endl; 
42    } 
43    void print2()
44    {
45       cout<<"this is test!" <<endl;
46    } 
47 };
48 
49 int main()
50 {
51    child ch(2);
52    ch.print();
53    return 0;
54 }

 

 

posted @ 2014-06-17 19:49  hjzqyx  阅读(1845)  评论(0编辑  收藏  举报