尝试在C++中实现基本类

Trying to implement a basic class in C++

本文关键字:实现 C++      更新时间:2023-10-16

我正在学习C++,目前正在尝试创建一个非常基本的类,代表船的长度和重量......似乎我在尝试将其拆分为头文件和 cpp 文件时遇到了问题。

这些是我正在使用的简单文件...

船:

#ifndef BOAT_H_
#define BOAT_H_
class Boat{
public:
    Boat();
    Boat(int,int);
private:
    int length;
    int weight;
};
#endif /* BOAT_H_ */

船.cpp:

#include "Boat.h"
Boat::Boat(){
    length = 25;
    weight = 2500;
}
Boat::Boat(int newLength, int newWeight){
    length = newLength;
    weight = newWeight;
}

编译时,我在 Boat 中收到错误.cpp关于它"首先在此处定义"。我一直在遵循教程并试图像他们一样做,但我似乎无法做到这一点。这是完整的错误消息。我错过了什么?

C:Documents and SettingsAdministrateurBureauWorkspaceClassTestsDebug/../Boat.cpp:4: multiple definition of `Boat::Boat()'
Main.o:C:Documents and SettingsAdministrateurBureauWorkspaceClassTestsDebug/..//Boat.cpp:4: first defined here
Boat.o: In function `Boat':
C:Documents and SettingsAdministrateurBureauWorkspaceClassTestsDebug/../Boat.cpp:4: multiple definition of `Boat::Boat()'
Main.o:C:Documents and SettingsAdministrateurBureauWorkspaceClassTestsDebug/..//Boat.cpp:4: first defined here
Boat.o: In function `Boat':
C:Documents and SettingsAdministrateurBureauWorkspaceClassTestsDebug/../Boat.cpp:9: multiple definition of `Boat::Boat(int, int)'
Main.o:C:Documents and SettingsAdministrateurBureauWorkspaceClassTestsDebug/..//Boat.cpp:9: first defined here
Boat.o: In function `Boat':
C:Documents and SettingsAdministrateurBureauWorkspaceClassTestsDebug/../Boat.cpp:9: multiple definition of `Boat::Boat(int, int)'
Main.o:C:Documents and SettingsAdministrateurBureauWorkspaceClassTestsDebug/..//Boat.cpp:9: first defined here

编辑:我把船.cpp包括在主要而不是船.h...问题解决了!谢谢!

没有办法确定你做了什么,但我确实设法用这个主函数生成了你的错误:

#include "Boat.h"
#include "Boat.cpp"
int main(int argc, const char *argv[])
{
    Boat b; 
    return 0;
}

按以下方式编译:

g++ -O0 -ggdb main.cpp  Boat.cpp -o main

这完全导致您报告的错误。无论你做了什么 - 你似乎已经尝试过两次包含Boat.cpp文件,通过这样做,你已经将你的 Boat 类的定义翻了一番。

似乎您在有函数 main 的模块中包含您的船.cpp文件。您只需要在带有 main 的模块中包含标头 boat.h。