问候哦,强大的编码器,
我是初学者,在这里有些麻烦。
有我的基础( sensor.h (:
class sensor
{
private:
int sensor_id;
string sensor_name;
string sensor_type;
float reading;
public:
sensor();
sensor(int, char*, char*);
~sensor();
/* Few extra methods here */
};
...我想创建其他4个从我的基础传感器继承的类(温度音调,湿度传感器 ...等(。
#include "sensor.h"
class temperaturesensor:public sensor
{
public:
Temperatursensor(int, char*,char*);
~Temperatursensor();
/* Few extra methods here */
};
thice是:这些类中的每一个都必须自行.cpp/.h文件,然后将其包含在我的 main.cpp 。。
中using namespace std;
#include <xyz.h>
/* Other libaries here */
....
#include "temperaturesensor.h"
#include "humiditysensor.h"
int main()
{
sensor* station[2];
station [0] = new temperaturesensor(x,y,z);
station [1] = new humiditysensor(x,y,z);
}
如果我包括其中之一,那不是大型。但是:如果我使用多个,我会遇到重新定义错误。
错误c2011:'传感器':'class'typeredefinition C: users name desktop project sensor.h 14
error c2011: 'temperaturesensor' : 'class' typeredefinition
我该怎么做才能解决这个问题?请注意,一旦
,我就不允许使用 #pragma对不起,我的愚蠢,谢谢!
您必须使用:
#ifndef FILE_H
#define FILE_H
.. normal code here
#endif
或
#pragma once
,但我认为,传感器也应该是抽象类,您也可以使用虚拟击路仪。还有一个认为,数组是从0。
您忘了在标题类中使用Include Guards,每次使用它,这都在重新定义您的基类。
所以,只做一个
#pragma once
或普通包括后卫
#ifndef YOURFILENAME_H
#define YOURFILENAME_H
.. normal code here
#endif
那么您将没有多重定义错误。
sensor
类的定义来自两个" heetaturesensor.h"one_answers" humitysensor.h"。使用警卫https://en.wikipedia.org/wiki/include_guard或 #pragma once
:https://en.wikipedia.org/wiki/wiki/pragma_once