【问题标题】:(Redefinition error) Create multiple inherting classes from one baseclass in C++(重定义错误)在C++中从一个基类创建多个继承类
【发布时间】:2017-06-29 15:51:17
【问题描述】:

您好,伟大的程序员,

我是初学者,在这里遇到了一些麻烦。

这是我的基类(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 个其他类继承自我的基类 sensor温度传感器、湿度传感器...等等)。

 #include "sensor.h"


class temperaturesensor:public sensor
{
public:
   Temperatursensor(int, char*,char*);
   ~Temperatursensor();

/* Few extra methods here */

};

问题是:这些类中的每一个都必须在其自己的 .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:“传感器”:“类”类型重新定义 c:\users\name\desktop\project\sensor.h 14

error c2011: 'temperaturesensor' : 'class' typeredefinition 

我可以做些什么来解决这个问题?请注意,我不允许使用一次#pragma

抱歉我的愚蠢,提前谢谢!

【问题讨论】:

  • 你可以使用标准的include guards代替不可移植的#pragma once
  • 欢迎来到 Stack Overflow。请花时间阅读The Tour 并参考Help Center 中的材料,您可以在这里问什么以及如何问。
  • 您的头文件中有include guards#pragma once 吗?
  • 你还记得吗,那个数组是从 0 开始计算的?
  • 您能否编辑您的问题显示错误?复制粘贴它们(作为文本)。

标签: c++ class inheritance redefinition


【解决方案1】:

你必须使用:

#ifndef FILE_H
#define FILE_H

.. normal code here

#endif

#pragma once

但我认为,该传感器也应该是抽象类,并且您应该使用虚拟析构函数。 另一种想法是数组是从 0 开始计算的。

【讨论】:

  • 数组索引的好方法!但是,我认为不需要抽象基类。
  • 不要创建前导下划线后跟大写字母those are reserved in all scopes的符号。
  • @AGNGazer 我看到该类抽象传感器和特定传感器的专业化
【解决方案2】:

你忘了在你的头类中使用包含保护, 这是在每次使用时重新定义基类。

所以,做一个

#pragma once

或普通的包含警卫

#ifndef YOURFILENAME_H
#define YOURFILENAME_H

.. normal code here

#endif

这样就不会出现多重定义错误了。

【讨论】:

    【解决方案3】:

    sensor 类的定义来自“temperaturesensor.h” 和“湿度传感器.h”。使用守卫https://en.wikipedia.org/wiki/Include_guard#pragma once: https://en.wikipedia.org/wiki/Pragma_once

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-21
      • 2015-03-10
      • 2011-02-21
      • 2013-05-22
      • 2011-09-09
      • 1970-01-01
      • 1970-01-01
      • 2013-07-27
      相关资源
      最近更新 更多