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

简介:
java中:
import java.util.Scanner;
public class ClassTest{
   public static void main(String args[]){
      child ch=new child(2);
      parent p=ch;
      p.print();
      //p.print2();//调用错误,父类中没有改成员方法,该方法只属于子类!
   }

class parent{
   int xx;
   parent(int x){
      xx=x;
   }
   void print(){
      System.out.println("this is parent!");
   }
   int f(){
      int n;
      Scanner s=new Scanner(System.in);
      n=s.nextInt();
      return n;
   }
}

class child extends parent{
   int xx;
   void print(){
      System.out.println("this is child!");
      System.out.println("父类中的f()函数得到的值:" + super.f());//当然也可以通过super来区分子类与父类同名函数的方法
      System.out.println("子类中的f()函数得到的值:" + f());
   }
   void print2(){
      System.out.println("this is test!");
   }
   child(int x){
      super(x);//调用父类的构造方法
      xx=5;
   }
   int f(){
      System.out.println("父类中的xx值:" + super.xx);//通过super.xxx可以区分子类与父类同名的变量
      System.out.println("子类中的xx值:" + xx);
      return 15;
   }
}
c++中:
#include<iostream> 
using namespace std;
class parent
{
public:
   int p;
   parent(int x)
   {
       p=x;
   }
   void print()
   {
      cout<<"this is parent" <<endl;
   } 
   int f()
   {
    return 11; 
   } 
}; 

class child : public parent
{
public:
   int p; 
   child(int x):parent(x)
   {
       p=15;
   }
   int f()
   {
      return 22;
   } 
   void print()
   {
       cout<<"this is child!" <<endl;
       cout<<"父类中的 p 变量值:"<<parent::p<<endl;
       cout<<"子类中的 p 变量值:"<<p<<endl; 
       
       cout<<"父类中的f()函数值:"<<parent::f()<<endl;
       cout<<"子类中的f()函数值:"<<f()<<endl; 
   } 
   void print2()
   {
      cout<<"this is test!" <<endl;
   } 
};

int main()
{
   child ch(2);
   ch.print();
   return 0;
}









本文转自 小眼儿 博客园博客,原文链接:http://www.cnblogs.com/hujunzheng/p/3793389.html,如需转载请自行联系原作者
目录
相关文章
|
2天前
|
存储 编译器 C语言
c++的学习之路:5、类和对象(1)
c++的学习之路:5、类和对象(1)
17 0
|
2天前
|
C++
c++的学习之路:7、类和对象(3)
c++的学习之路:7、类和对象(3)
19 0
|
3天前
|
Java 关系型数据库 MySQL
Elasticsearch【问题记录 01】启动服务&停止服务的2类方法【及 java.nio.file.AccessDeniedException: xx/pid 问题解决】(含shell脚本文件)
【4月更文挑战第12天】Elasticsearch【问题记录 01】启动服务&停止服务的2类方法【及 java.nio.file.AccessDeniedException: xx/pid 问题解决】(含shell脚本文件)
28 3
|
1天前
|
设计模式 Java C++
【C++高阶(八)】单例模式&特殊类的设计
【C++高阶(八)】单例模式&特殊类的设计
|
1天前
|
编译器 C++
【C++基础(八)】类和对象(下)--初始化列表,友元,匿名对象
【C++基础(八)】类和对象(下)--初始化列表,友元,匿名对象
|
5天前
|
存储 Java
Java动态转发代理IP的实现方法
Java动态转发代理IP的实现方法
21 11
|
5天前
|
存储 安全 C语言
【C++】string类
【C++】string类
|
6天前
|
Java
Java接口中可以定义哪些方法?
【4月更文挑战第13天】
10 0
Java接口中可以定义哪些方法?
|
存储 编译器 Linux
标准库中的string类(中)+仅仅反转字母+字符串中的第一个唯一字符+字符串相加——“C++”“Leetcode每日一题”
标准库中的string类(中)+仅仅反转字母+字符串中的第一个唯一字符+字符串相加——“C++”“Leetcode每日一题”
|
7天前
|
编译器 C++
标准库中的string类(上)——“C++”
标准库中的string类(上)——“C++”