【发布时间】:2020-02-21 09:35:51
【问题描述】:
我有一个大学项目,我设法使用自己的 makefile/终端命令开始工作。但是我在大学的自动标记上得了零分。我认为这是因为他们使用了一个 makefile,它试图在编译器的一行中执行所有三个 cpp 文件(如果这甚至可能的话),这很难说,因为标记没有给出任何反馈。当我尝试编译所有三个 .cpp 文件(g++ main.cpp A.cpp B.cpp)时,我收到以下错误消息:
- B.cpp:4:3:错误:重新定义“T B::getVal()” T B::getVal(){
- A.cpp:4:6:错误:重新定义“void A::print(B)” void A::print(B bInstance){
在我的 MRE 中,以下内容需要保持不变:
- A 和 B 必须有 .h 和 .cpp 文件
- main.cpp 只能包含“A.h”
- A 必须要求 B 才能工作
这是我的 MRE: - 它创建 B 的实例,然后使用 A 的实例打印具有实例 B 值的消息。
main.cpp
#include "A.h"
int main(){
B<char> b1;
b1.val='B';
A<char> a1;
a1.print(b1);
}
啊.h
#ifndef AAAA
#define AAAA
#include<iostream>
#include "B.h"
using namespace std;
template <class T>
class A{
public:
void print(B<T> bInstance);
};
#include "A.cpp"
#endif
A.cpp
#include "A.h"
template <class T>
void A<T>::print(B<T> bInstance){
cout<<"I am A, and I am using "<<bInstance.getVal()<<endl;
}
B.h
#ifndef BBBB
#define BBBB
template <class T>
class B{
public:
T val;
T getVal();
};
#include "B.cpp"
#endif
B.cpp
#include "B.h"
template <class T>
T B<T>::getVal(){
return val;
}
工作编译和运行命令
g++ main.cpp
./a.out
它应该使用的命令(如果可能的话)
g++ main.cpp A.cpp B.cpp
./a.out
【问题讨论】:
-
我还是新手,我意识到我用太多词来描述我的问题。我试图减少它,但如果这仍然太多,请告诉我。
-
不包含 cpp 文件。
标签: c++ linux templates header linker