尝试在C++中实现基本类
Trying to implement a basic class in C++
我正在学习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。
相关文章:
- 如果没有malloc,链表实现将失败
- 如何在c++中实现处理器调度模拟器
- 如何在c++中使用引用实现类似python的行为
- 实现无开销push_back的最佳方法是什么
- 使用简单类型列表实现的指数编译时间.为什么
- 如何在BST的这个简单递归实现中消除警告
- 实现一个在集合上迭代的模板函数
- 我应该实现右值推送功能吗?我应该使用std::move吗
- 如何正确实现和访问运算符的各种自定义枚举器
- C++Union/Struct位域的实现和可移植性
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 在c++中实现LinkedList时,应出现未处理的错误
- 为左值和右值的包装器实现C++范围
- 使用模板进行堆栈实现; "name followed by :: must be a class or namespace"
- 使用GSoap实现ONVIF
- 在用于格式4的arm模拟器中实现功能时的一个问题
- 用于AVX的ln(x)的实现,m256
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 在C++中,如何在类和函数(可能是模板化的)的头中编写完整的实现
- std::random_device是如何实现的