c++第四次做业

派生类ios

定义方式: class 派生类名    基类名1,继承方式  基类名2,继承方式...函数

{this

    派生类成员声明;spa

}code

类的继承blog

对于类之间可以相互继承,分别是公有继承,私有继承,以及保护继承。继承

公有继承接口

继承所有类的成员可是对于基类的私有类没法进行直接访问,只能经过基类函数进行使用。get

例如:io

#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();}

相关文章
相关标签/搜索