1.在派生类中,确实继承了基类的私有成员,这一点可以通过派生类的大小看出来
2.但是,我们,是用不了的,根本不能使用那个变量(除非用指针操作地址)
3.一般,可以在派生类中定义重名的变量,不会报错,主要是作用域的前缀将它两区别开
4.其实,我们也可以在派生类中调用从基类中继承过来的公有函数,间接的访问那些不可见的变量,如果返回值是引用的话,甚至可以加以修改
//也可能虽然继承了,但是不可见
#include<iostream>
#include<string>
using namespace std;
//学生基类
class stu
{
private:
string name;
int score;
public:
//构造函数
stu(string name_) :name(name_) {
cout << "调用了stu基类的有参构造函数" << endl;
};
//默认构造
stu() {
this->name = "无名氏";
cout << "调用了stu基类的默认构造函数" << endl;
};
void show()
{
cout << "my name is" << this->name << endl;
}
string& getName()
{
return this->name; //返回基类name变量 引用的公有接口
}
};
//研究生派生类
class gra_stu:public stu
{
private:
string thesis;
string name="李四";
public:
//构造函数
gra_stu() {
thesis = "about computer!";
//this->name = "zhang san";--报错
//this->stu("张三"); --报错,没有继承stu基类的构造函数
//getName() = "张三"; //成功利用返回 基类私有成员的引用的方式 给派生类 中继承到的不可见的变量赋值
//不过,这么做和 将原来基类中的私有变量定义为 公有的区别不大
}
void show2()
{
this->show();
cout << "my real name is" << this->name << endl;
cout << "my thesis is " << this->thesis << endl;
}
};
//既然有不可见的变量,那么,我可不可以在派生类中定义重名的变量呢??
//事实证明是可以,其实将这两个变量区别开的,就是它的作用域符号,这个类的作用域符号下,就是派生类的作用域中的
//那个新定义的name变量
int main()
{
//测试:
gra_stu test;
test.show2();
return 0;
}