C++语言基础 例程 基类与派生类的转换

简介: 贺老师的教学链接  本课讲解指向基类对象的指针变量也可以指向派生类对象#include <iostream>#include <string>using namespace std;class Student//声明Student类{public: Student(int, string,float); void display( );

贺老师的教学链接  本课讲解


指向基类对象的指针变量也可以指向派生类对象

#include <iostream>
#include <string>
using namespace std;
class Student//声明Student类
{
public:
    Student(int, string,float);
    void display( );
private:
    int num;
    string name;
    float score;
};

Student::Student(int n, string nam,float s)
{
    num=n;
    name=nam;
    score=s;
}

void Student::display( )
{
    cout<<endl<<"num:"<<num<<endl;
    cout<<"name:"<<name<<endl;
    cout<<"score:"<<score<<endl;
}

class Graduate:public Student
{
public:
    Graduate(int, string ,float,float);
    void display( );
private:
    float pay;
};

Graduate::Graduate(int n, string nam,float s,float p):Student(n,nam,s),pay(p) { }

void Graduate::display()
{
    Student::display();
    cout<<"pay="<<pay<<endl;
}

int main()
{
    Student stud1(1001,"Li",87.5);
    Graduate grad1(2001,"Wang",98.5,563.5);
    Student *pt=&stud1;
    pt->display( );
    pt=&grad1;
    pt->display( );
    return 0;
}


目录
相关文章
|
20天前
|
存储 C++ 容器
C++入门指南:string类文档详细解析(非常经典,建议收藏)
C++入门指南:string类文档详细解析(非常经典,建议收藏)
31 0
|
20天前
|
存储 编译器 C语言
C++入门: 类和对象笔记总结(上)
C++入门: 类和对象笔记总结(上)
30 0
|
1天前
|
C++
【C++成长记】C++入门 | 类和对象(下) |Static成员、 友元
【C++成长记】C++入门 | 类和对象(下) |Static成员、 友元
|
1天前
|
存储 编译器 C++
【C++成长记】C++入门 | 类和对象(中) |拷贝构造函数、赋值运算符重载、const成员函数、 取地址及const取地址操作符重载
【C++成长记】C++入门 | 类和对象(中) |拷贝构造函数、赋值运算符重载、const成员函数、 取地址及const取地址操作符重载
|
10天前
|
程序员 C++
C++语言模板学习应用案例
C++模板实现通用代码,以适应多种数据类型。示例展示了一个计算两数之和的模板函数`add&lt;T&gt;`,可处理整数和浮点数。在`main`函数中,展示了对`add`模板的调用,分别计算整数和浮点数的和,输出结果。
10 2
|
10天前
|
存储 算法 C语言
【C++初阶】8. STL初阶 + String类
【C++初阶】8. STL初阶 + String类
45 1
|
10天前
|
C语言 C++
【C++初阶】9. string类的模拟实现
【C++初阶】9. string类的模拟实现
36 1
|
18天前
|
存储 安全 编译器
【C++】类的六大默认成员函数及其特性(万字详解)
【C++】类的六大默认成员函数及其特性(万字详解)
33 3
|
20天前
|
C++
4. C++类的组合
4. C++类的组合
26 0
|
20天前
|
编译器 C语言 C++
【c++】类和对象(三)构造函数和析构函数
朋友们大家好,本篇文章我们带来类和对象重要的部分,构造函数和析构函数

热门文章

最新文章