c++ - 类的重新定义

标签 c++

我得到了三个.cpp 文件和两个头文件。

但是当我编译它们时,即 Point.cpp、Data.cpp 和 main.cpp,它会说

Data.h:6:7 redefinition of Data at 'Data.h'
Data.h:6:7 previously definition of 'class Data'

下面是我的Data.h(以前在上面称为2.h)

#include <iostream>
#include <string>

using namespace std;

class Data
{
private:
string sType;
public:
Data();
Data(string);
void setSType(string);
string getSType();
};

下面是我的data.cpp

#include "Data.h"

Data::Data()
{
sType = "";
}

Data::Data(string s)
{
sType = s;
}

void Data::setSType(string ss)
{
sType = ss;
}

string Data::getSType()
{
return sType;
}

下面是我的PointD.h(以前称为3.h)

#include <iostream>
#include <string>
#include "Data.h"

using namespace std;

class PointD
{
private:
int x
Data data1;
public:
PointD();
PointD(int,Data);

void setX(int);
void setData(Data);

int getX();
Data getData();
};

下面是我的PointD.cpp

#include "PointD.h"

PointD::PointD()
{
x = 0;
}

PointD::PointD(int xOrdinate,Data dd)
{
x = xOrdinate;
data1 = dd;
}

void PointD::setXordinate(int Xordinate)
{
x = Xordinate;
}

void PointD::setData(Data dd)
{
data1 = dd;
};

int PointD::getXordinate()
{
return x;
}

Data PointD::getData()
{
return data1;
}

这是我的main.cpp

#include <iostream>
#include <string>

#include "Data.h"
#include "PointD.h"
using namespace std;

int main()
{
const int MAX_NUM = 20;

Data ldata[MAX_NUM];
PointD pointd[MAX_NUM];

//more codes..
}

但是当我编译它们时,即 Point.cpp、Data.cpp 和 main.cpp,它会说

Data.h:6:7 redefinition of Data at 'Data.h'
Data.h:6:7 previously definition of 'class Data'

谁能告诉我这里到底出了什么问题..

最佳答案

你需要使用 include guards,或者最简单的:

 #pragma once

在你的头文件中

参见 Purpose of Header guards更多背景

想法:1.hpp

#ifndef HEADER_GUARD_H1_HPP__
#define HEADER_GUARD_H1_HPP__

// proceed to declare ClassOne

#endif // HEADER_GUARD_H1_HPP__

关于c++ - 类的重新定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12786233/

相关文章:

c++ - 将 friend 从模板导出到全局命名空间

c++ - 无序映射相等功能 c++

c++ - C++中的模板类

c++ - 如何将整数和小数分隔为两个不同的变量

c++ - 在 GDB 中抛出特定异常类型时如何中断?

c++ - 字符串转换为 const char * 问题

c++ - & 在函数声明返回类型

c++ - 基类可以有一个成员是派生类的实例吗?

c++ - 解决 8 拼图游戏

全息镜头中的 C++ dll