c++第四次作业
派生类
定义方式: class 派生类名 基类名1,继承方式 基类名2,继承方式...
{
派生类成员声明;
}
类的继承
对于类之间能够相互继承,分别是公有继承,私有继承,以及保护继承。
公有继承
继承全部类的成员但是对于基类的私有类无法进行直接访问,只能通过基类函数进行使用。
例如:
#include <iostream>
#include <math.h>
using namespace std;
class point
{
public:
void set1(int x, int y);
void show();
int getx()
{
return x;
};
int gety()
{
return y;
};
private:
int x;
int y;
};
void point::set1(int x, int y)
{
this->x = x;
this->y = y;
}
void point::show()
{
cout << "x=" << x << endl << "y=" << y << endl;
}
class line :public point
{
public:
void set(int x,int y);
float todis();
private:
float dis;
};
void line::set(int x, int y)
{
set1(x,y);
}
float line::todis()
{
dis = sqrt((getx() * getx()) + (gety() * gety()));
return dis;
}
int main()
{
line a;
a.set(3, 4);
a.show();
cout << a.todis() << endl;
}
其中point类中的show函数是可以被直接调用的。
私有继承
对于私有继承,基类的共有成员与保护成员以私有成员的形式出现在派生类中,但是对于基类的私有成员依然无法进行直接访问
例如
#include <iostream> #include <math.h> using namespace std; class point { public: void set1(int x, int y); void show(); int getx() { return x; }; int gety() { return y; }; private: int x; int y; }; void point::set1(int x, int y) { this->x = x; this->y = y; } void point::show() { cout << "x=" << x << endl << "y=" << y << endl; } class line :private point { public: void set(int x,int y); float todis(); void show1(); private: float dis; }; void line::set(int x, int y) { set1(x,y); } float line::todis() { dis = sqrt((getx() * getx()) + (gety() * gety())); return dis; } void line::show1() { cout << dis<<endl; show(); } int main() { line a; a.set(3, 4); cout << a.todis() << endl; a.show1(); }
其中无法直接直接调用line类 a无法直接使用point中的show函数必须在重新创建接口函数
保护继承
对于保护继承,基类的共有成员与保护成员以保护成员的形式出现在派生类中,但是对于基类的私有成员依然无法进行直接访问
例如
#include <iostream>
#include <math.h>
using namespace std;
class point
{
public:
void set1(int x, int y);
void show();
int getx()
{
return x;
};
int gety()
{
return y;
};
private:
int x;
int y;
};
void point::set1(int x, int y)
{
this->x = x;
this->y = y;
}
void point::show()
{
cout << "x=" << x << endl << "y=" << y << endl;
}
class line :protected point
{
public:
void set(int x,int y);
float todis();
void show1();
private:
float dis;
};
void line::set(int x, int y)
{
set1(x,y);
}
float line::todis()
{
dis = sqrt((getx() * getx()) + (gety() * gety()));
return dis;
}
void line::show1()
{
cout << dis<<endl;
show();
}
int main()
{
line a;
a.set(3, 4);
cout << a.todis() << endl;
a.show1();
}