我的问题更多是在这种特定情况下适用的概念/学习方法。我正在做作业,并且有一个名为sensor的类和一个名为digitalSensor的派生类。传感器的数据成员之一是“正在运行”。而且,当我为digitalSensor实现打印功能时,我需要根据数字传感器是否“正在运行”来打印一行。
本质上,我需要在digitalSensor中创建一条if语句,以检查“功能”的值。但是Xcode告诉我“功能是传感器的私有成员”。由于digitalSensor是从传感器派生的,因此它也不应该具有“功能性”成员变量吗?在创建digitalSensor打印功能时如何检查它?
这是我的sensor.h文件:
#ifndef __Program_6__sensor__
#define __Program_6__sensor__
#include <iostream>
class sensor {
char* SensorName;
float energyDraw;
int functioning;
int onoff;
public:
sensor(char*n, float pc);
virtual void print();
void setOK(int K);
int getOK();
void setOnOff(int n);
int getOnOff();
};
//---------
class digitalSensor : public sensor {
int reading;
public:
digitalSensor(char*n, float pc);
virtual void print();
void setCurrentReading(int r);
int getCurrentReading();
};
class analogSensor : public sensor {
int Reading;
int minRead;
int maxRead;
public:
analogSensor(char *n, float pc, int mm, int mx);
virtual void print();
void setCurrentReading(int r);
int getCurrentReading();
};
#endif /* defined(__Program_6__sensor__) */
这是我的sensor.cpp文件,我在打印功能上的工作在底部:
#include "sensor.h"
#include "definitions.h"
using namespace std;
//--------SENSOR CLASS------------//
sensor::sensor(char *n, float pc) {
SensorName = (char*)malloc(strlen(n)+1);
energyDraw = pc;
functioning = WORKING;
onoff = OFF;
}
void sensor::print() {
cout << " Sensor: " << SensorName;
cout << " Power Consumption: " << energyDraw;
if (functioning == WORKING) {
cout << "\nSensor is functioning correctly\n";
if (onoff == ON) {
cout << "Sensor is On";
}
if (onoff == OFF) {
cout << "Sensor is Off";
}
}
if (functioning == NOTWORKING) {
cout << "Sensor is not functioning correctly";
}
}
void sensor::setOK(int k) {
functioning = k;
}
int sensor::getOK() {
return functioning;
}
void sensor::setOnOff(int n) {
onoff = n;
}
int sensor::getOnOff() {
return onoff;
}
//---------------------------------//
//*********DIGITAL SENSOR**********//
digitalSensor::digitalSensor(char *n, float pc) : sensor(n, pc){
reading = OFF;
}
void digitalSensor::print() {
sensor::print();
if (functioning == WORKING && onoff == ON) {
cout << "Current sensor reading is: " << reading;
}
if (digitalSensor.functioning == WORKING && digitalSensor.onoff == OFF) {
cout << "Current reading not available";
}
}
错误是在“ void digitalSensor :: print()”之后的最后两行。
感谢大家的帮助!一旦我学到了这些东西,我一定会回报和回答新手问题!
最佳答案
在C ++中,class
成员的默认可见性为private
,这意味着无法从外部甚至从子类访问字段和方法。解决方案是将相关字段标记为protected
(与private
相同,但可以从子类访问):
class sensor {
protected:
char* SensorName;
float energyDraw;
int functioning;
int onoff;
public:
sensor(char*n, float pc);
virtual void print();
void setOK(int K);
int getOK();
void setOnOff(int n);
int getOnOff();
};