在认识C++基本语句结构的基础上,了解类成员,并使用类成员编写一个简单的程序。主要用到以下知识点;
1.类成员使用及派生类的使用
2.头文件的使用。
我们通过类来定义自己的数据结构,类定义以关键字class或struct开始(class和struct关键字的差别在于默认访问级别,默认情况下,struct的成员为public,class成员private),其后是该类的名字标识符。类体位于花括号里面,花括号后面必须要跟一个分号。
类体可以为空,类体定义组成了该类型的数据和操作,这些操作和数据是类的一部分,也称为类的成员。操作称为成员函数,而数据则称为数据成员。
类中private 和 public称为访问标号,访问标号控制类的成员在类外部是否可访问,使用该类的代码可能只能访问public成员。
类的一个重要的特点是可以继承,派生类可以继承基类的某些特性以及数据成员,具体的书写格式如下:
class function :public library
其中 library 是已经定义好的类,可以称之为基类。function为新定义的类,也叫派生类。
我们利用类来编写程序存放图书的IBSN, 价格,以及书名,输出相关信息,要求如下:
1.要求使用类成员存放IBSN码,价格,书名
2.要求包含头文件
3.要求使用派生类
头文件代码如下
#ifndef hanrui
#define hanrui
#include <iostream>
#include <string>
using namespace std;
class library
{
public:
int price;
int IBSN;
string name;
library()
{
cout << "请输入价格" << endl;
cin >> price;
cout << "请输入IBSN" << endl;
cin >> IBSN;
cout << "图书名" << endl;
cin >> name;
}
};
class function :public library
{
public:
//显示派生类的值
void outputp()
{
cout << "the price is " << " " << price << endl;
}
void outputI()
{
cout << "the IBSN is " << " " << IBSN<< endl;
}
void outputN()
{
cout << "the name is " << " " << name << endl;
}
};
#endif
CPP程序如下
# include<string>
# include <iostream>
# include "1.h"
using namespace std;
int main()
{
function test;
test.outputN();
return 0;
}
运行后,手动输入图书相关信息后,可以输出图书IBSN,信息,名字等