如有帮助,请采纳。
#include<iostream>
using namespace std;
class Person
{
public:
void run();
void swim();
};
class Student : public Person
{
public:
void run();
};
void Person::run()
{
cout<<"person run"<<endl;
}
void Person::swim()
{
cout<<"person swim"<<endl;
}
void Student::run()
{
cout<<"student run"<<endl;
}
int main()
{
Student st;
st.Person::run();
return 0;
}5:下面是继承派生之间的互相访问,你理解下面这段代码,你就清楚继承和派生的精髓了
#include<iostream>
using namespace std;
class Base
{
friend class Derived2;//friend
int x;
protected://protected
int y;
};
class Derived1:Base//private继承
{
public:
/* int getx()
{
return x;//不合法,访问基类的private成员
}*/
int gety()
{
return y;//合法,访问基类的protected成员
}
};
class Derived2:Base//private继承
{
public:
int getx();
};
int Derived2::getx()
{
return x;//友员直接访问基类的私有成员
}
class Derived3:public Base//public继承
{
public:
/*
int getx()
{
return x;//在这里还是不能访问,因为x是Base的private成员,只在Base里可以访问,在外面不可以被访问。
}
*/
int gety()
{
return y;
}
};
int main()
{
int i;
Derived2 ob;//没有带参数的构造函数或成员函数初始化x,构造函数赋个随机值给x
i=ob.getx();
cout<<i<<endl;
Derived3 ob3;
i=ob3.gety();
cout<<i<<endl;
system("pause");
}