c 中子类能否访问父类成员_C/C++ 子类调用父类中的私有成员变量(对比JAVA)

本文展示了C++和JAVA中类的继承概念,以Person和Man为例,探讨了子类如何访问父类的私有成员。在C++中,Man通过`Person::getAge()`访问父类Person的私有属性age;而在JAVA中,Male通过`super.getAge()`调用父类Person的getAge()方法。这两个示例突显了面向对象编程中继承和封装的特性。
摘要由CSDN通过智能技术生成

C++

Person中age为私有的,通过Persron::getAge()可以获取age的值。

#include

using namespace std;

class Person

{

public:

Person(int a) {

this->age = a;

}

int getAge() {

return age;

}

private:

int age;

};

class Man : public Person

{

public:

Man(string name, int add, int age):Person(age) {

this->name = name;

this->add = add;

}

int getAge() {

return add + Person::getAge();

}

string getName() {

return name;

}

private:

string name;

int add;

};

int main()

{

Man m1("Test", 12, 15);

cout << m1.getName() << " " << m1.getAge() << endl;

return 0;

}

JAVA:使用super调用父类的读域函数getAge()

Person.java

package test;

public class Person {

public Person(int age) {

this.aAge = age;

}

public int getAge() {

return aAge;

}

public void setAge(int age) {

aAge = age;

}

private int aAge;

}

Male.java

package test;

public class Male extends Person

{

public Male(int age, int add) {

super(age);

this.add = add;

}

public int getAge() {

return this.add + super.getAge();

}

private int add;

public static void main(String[] args) {

System.out.println(new Male(12, 15).getAge());

}

}

~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值