C++ 错误:定义了两个具有头文件的类时重新定义类
我正在尝试运行一个教程。其中两个类定义为两个.h文件和两个.cpp文件。代码如下所示。我不知道为什么它会给我错误 班级生日工作正常,但当我添加班级成员,班级成员使用班级生日时,它会给我带来错误。 我仔细检查了一些关于重新定义错误的帖子,比如包括guard等等,这些东西在我的代码中是可以的。 我使用这些行来编译和运行VisualStudio代码中的代码C++ 错误:定义了两个具有头文件的类时重新定义类,c++,C++,我正在尝试运行一个教程。其中两个类定义为两个.h文件和两个.cpp文件。代码如下所示。我不知道为什么它会给我错误 班级生日工作正常,但当我添加班级成员,班级成员使用班级生日时,它会给我带来错误。 我仔细检查了一些关于重新定义错误的帖子,比如包括guard等等,这些东西在我的代码中是可以的。 我使用这些行来编译和运行VisualStudio代码中的代码 g++ -c People.cpp -o People.o g++ -c Birthday.cpp -o Birthday.o g++ -c ma
g++ -c People.cpp -o People.o
g++ -c Birthday.cpp -o Birthday.o
g++ -c main.cpp -o main.o
g++ main.o Birthday.o -o prog
./prog
#ifndef BIRTHDAY_H
#define BITHDAY_H
using namespace std;
class Birthday
{
public:
Birthday(int d, int m, int y );
void printdate();
private:
int day;
int month;
int year;
};
#endif
#include "Birthday.h"
#include <iostream>
using namespace std;
Birthday::Birthday(int m, int d, int y)
{
day = d;
month = m;
year = y;
}
void Birthday:: printdate()
{
cout << day <<"/" << month << "/" << year <<endl;
}
#ifndef PEOPLE_H
#define PEOPLE_H
#include "Birthday.h"
#include <string>
using namespace std;
class People
{
public:
People(string x, Birthday bo);
void printinfo();
private:
string name;
Birthday dateofbirth;
};
#endif
#include "People.h"
#include <iostream>
#include "Birthday.h"
using namespace std;
People::People(string x, Birthday bo)
:
name (x),
dateofbirth(bo)
{
}
void People::printinfo()
{
cout << name << "was born on " <<endl;
cout << "Birthday is :";
dateofbirth.printdate();
}
#include <iostream>
#include "Birthday.h"
#include "People.h"
using namespace std;
int main()
{
Birthday birthobj(12,5,1995);
birthobj.printdate();
People Peoplename("Muhammad Adil", birthobj);
Peoplename.printinfo();
}
g++-c People.cpp-o People.o
g++-c birth.cpp-o birth.o
g++-c main.cpp-o main.o
g++main.o birth.o-o prog
/进度
#伊芬迪夫生日酒店
#定义比特日
使用名称空间std;
班级生日
{
公众:
生日(整数d,整数m,整数y);
作废打印日期();
私人:
国际日;
整月;
国际年;
};
#恩迪夫
#包括“生日.h”
#包括
使用名称空间std;
生日:生日(整数m,整数d,整数y)
{
d=d;
月=m;
年份=y;
}
作废生日::打印日期()
{
cout您没有正确定义收割台护罩
#ifndef BIRTHDAY_H
#define BITHDAY_H
应该是
#ifndef BIRTHDAY_H
#define BIRTHDAY_H
使用#pragma一次
会更好,因为它可以避免这样的打字错误。标题保护
是解决您提到的重新定义问题所必需的
您的生日
类头文件应位于头保护
中,如下所示:
#ifndef BIRTHDAY_H
#define BIRTHDAY_H
using namespace std;
class Birthday
{
public:
Birthday(int d, int m, int y );
void printdate();
private:
int day;
int month;
int year;
};
#endif
正如上面代码中所示:
不正确的行#define BITHDAY_H
更改为#define BITHDAY_H
所以,除了上面的打字错误之外,代码中的其他内容似乎都是正确的
我希望这会有帮助!您的定义与ifndef不匹配(\ifndef BITHDAY\u H\define BITHDAY\u H
)请注意定义中缺少的r,它还避免了可移植性。是的,很遗憾它不标准,因为它在某些环境中无法正常工作。