类的成员的访问权限:
public:父类成员,被集成到子类后,访问权限都不变
private:父类成员,被继承到子类后,访问权限都变为private
protected:父类成员,被继承到子类后,public权限的成员降级为protected,其他不变
练习 2:
某无线通信设备 ODU
查看发射功率, 设置发射功率, 查看发射频率, 设置发射频率, 查看带宽, 修改带宽, 查看设备概述(各指标的值).
后来对该产品做了升级, 研发了 ODU330 产品:
这个产品, 新增加了以下功能: 查看当前的误
码率. 查看误码率告警门限 设置误码率告警门限
ODU.h
#pragma once
#include <string>
#include<iostream>
using namespace std;
class ODU
{
public:
ODU();
~ODU();
float getTxPower();
int getTxFreq();
float getBandWidth();
bool setTxPower(float power);
bool setTxFreq(int frequency);
bool setBandWidth(float bandWidth);
string description();
protected:
float txPower; // 发射功率
int txFreq; //发射频率
float bandWidth; //带宽, 单位:M
};
ODU.cpp
#include "ODU.h"
#include <sstream>
using namespace std;
ODU::ODU()
{
}
ODU::~ODU()
{
}
float ODU::getTxPower()
{
return txPower;
}
bool ODU::setTxPower(float power)
{
// 实际产品项目中, 是通过串口发送控制包实现的. txPower = power;
return true;
}
int ODU::getTxFreq()
{
return txFreq;
}
bool ODU::setTxFreq(int frequency)
{
txFreq = frequency;
return true;
}
float ODU::getBandWidth()
{
return bandWidth;
}
bool ODU::setBandWidth(float bandWidth)
{
this->bandWidth = bandWidth;
return true;
}
string ODU::description()
{
stringstream ret;
ret << "发射功率: " << txPower << "\t 发射频率: " << txFreq<< "\t 带宽: " << bandWidth;
return ret.str();
}
ODU330.h
#pragma once
#include <string>
#include "ODU.h"
using namespace std;
class ODU330 : public ODU
{
public:
ODU330();
~ODU330();
float getWarnThreshold();
bool setWarnThreshold(float threshold);
float getBER(); //获取当前误码率
string description();
private:
float warnThreshold; //告警门限
};
ODU330.cpp
#include <sstream>
#include "ODU330.h"
ODU330::ODU330()
{
}
ODU330::~ODU330()
{
}
float ODU330::getWarnThreshold()
{
return warnThreshold;
}
bool ODU330::setWarnThreshold(float threshold)
{
warnThreshold = threshold;
return true;
}
float ODU330::getBER()
{
return 0.00005f; //模拟值
}
string ODU330::description()
{
stringstream ret;
ret << "发射功率: " << txPower << "\t 发射频率: " << txFreq<< "\t 带宽: " << bandWidth << "\t 误码率: " << getBER()<< "\t 告警门限: " << warnThreshold;
return ret.str();
}
test.cpp
#include<iostream>
#include"ODU.h"
#include"ODU330.h"
using namespace std;
int main()
{
ODU odu1;
odu1.setBandWidth(500);
odu1.setTxFreq(114000);
odu1.setTxPower(45);
cout << odu1.description() << endl;
ODU330 odu2;
odu2.setBandWidth(600);
odu2.setTxFreq(119000);
odu2.setTxPower(48);
odu2.setWarnThreshold(0.0001);
cout << odu2.description() << endl;
return 0;
}
输出流stringstream需要头文件#include<sstream>,stringstream ret;ret的输出类似于cout,同时要注意输出的方向和cout是相同的<<,最后转化为字符串输出,ret.str();