类继承
hi,大家好,我是爱吃香蕉的猴子,今天记录一下类继承
从一个类派生出另一个类时,原始类称为基类,继承类成为派生类。说明继承,首先需要一个基类.
const关键字的作用:
1) 欲阻止一个变量被改变,可使用const,在定义该const变量时,需先初始化,以后就没有机会改变他了;
2)对指针而言,可以指定指针本身为const,也可以指定指针所指的数据为const,或二者同时指定为const;
3)在一个函数声明中,const可以修饰形参表明他是一个输入参数,在函数内部不可以改变其值;
4)对于类的成员函数,有时候必须指定其为const类型,表明其是一个常函数,不能修改类的成员变量;
5)对于类的成员函数,有时候必须指定其返回值为const类型,以使得其返回值不为“左值”。
先写例子:
//
// Created by cao.yongren on 2021/5/27.
//
#ifndef INC_13_TABTENN0_H
#define INC_13_TABTENN0_H
#include <string>
using std::string;
class TableTennisPlayer {
private:
string firstName;
string lastName;
bool hasTable;
public:
TableTennisPlayer (
const string & fn = "none",
const string & ln = "none",
bool ht = false);
void Name() const;
bool HashTable() const {
return hasTable;
}
void ResetTable (bool v) {
hasTable = v;
}
};
//要使用派生类,程序必须要能够访问基类的声明。将两个类的声明置于同一个文件;
//继承
class RatedPlayer : public TableTennisPlayer {
private:
unsigned int rating;
public:
RatedPlayer (
unsigned int r = 0,
const string & fn = "none",
const string & ln = "none",
bool ht = false);
RatedPlayer(unsigned int r, const TableTennisPlayer & tp);
unsigned int Rating() const {
return rating;
}
void ResetRating (unsigned int r) {
rating = r;
};
};
#endif //INC_13_TABTENN0_H
#include <iostream>
#include "tabtenn0.h"
/**
* TableTeenisPlayer类只是记录会员的姓名以及是否有桌球
* */
TableTennisPlayer ::TableTennisPlayer(const string &fn, const string &ln, bool ht) {
firstName = fn;
lastName = ln;
hasTable = ht;
}
void TableTennisPlayer::Name() const {
std::cout << lastName << ", " << firstName;
}
RatedPlayer::RatedPlayer(unsigned int r, const string &fn, const string &ln, bool ht) :
TableTennisPlayer(fn, ln, ht) {
rating = r;
}
RatedPlayer::RatedPlayer(unsigned int r, const TableTennisPlayer &tp) : TableTennisPlayer(tp) {
}
//
// Created by cao.yongren on 2021/5/27.
//
#include "iostream"
#include "tabtenn0.h"
int main (void) {
using std::cout;
TableTennisPlayer player1 {"Chuck", "Blizzard", true};
TableTennisPlayer player2 {"Tara", "Boomdea", false};
RatedPlayer rPlayer1 {1140, "Malley", "Duck", true};
rPlayer1.Name();
if (rPlayer1.HashTable()) {
cout << ": has a table.\n";
} else {
cout << "hasn't a table\n";
}
player1.Name();
if (player1.HashTable()) {
cout << ": has a table \n";
} else {
cout << ": hasn't a table";
}
player2.Name();
if (player2.HashTable())
cout << ": has a table";
else
cout << ": hasn't a table .\n";
return 0;
}
Code的搬运工V1.0