鉴于此代码示例:
complex.h:
#ifndef COMPLEX_H
#define COMPLEX_H
#include <iostream>
class Complex
{
public:
Complex(float Real, float Imaginary);
float real() const { return m_Real; };
private:
friend std::ostream& operator<<(std::ostream& o, const Complex& Cplx);
float m_Real;
float m_Imaginary;
};
std::ostream& operator<<(std::ostream& o, const Complex& Cplx) {
return o << Cplx.m_Real << " i" << Cplx.m_Imaginary;
}
#endif // COMPLEX_H
Run Code Online (Sandbox Code Playgroud)
complex.cpp:
#include "complex.h"
Complex::Complex(float Real, float Imaginary) {
m_Real = Real;
m_Imaginary = Imaginary;
}
Run Code Online (Sandbox Code Playgroud)
main.cpp:
#include "complex.h"
#include <iostream>
int main()
{
Complex …Run Code Online (Sandbox Code Playgroud) 我就是不明白为什么这不会编译。
我有三个文件:
主程序
#include "expression.h"
int main(int argc, char** argv)
{
return 0;
}
Run Code Online (Sandbox Code Playgroud)
表达式.h
#ifndef _EXPRESSION_H
#define _EXPRESSION_H
namespace OP
{
char getSymbol(const unsigned char& o)
{
return '-';
}
};
#endif /* _EXPRESSION_H */
Run Code Online (Sandbox Code Playgroud)
和表达式.cpp
#include "expression.h"
Run Code Online (Sandbox Code Playgroud)
(Ofc 里面还有更多内容,但即使我评论除了#includeout之外的所有内容,它也不起作用)
我编译它
g++ main.cpp expression.cpp -o main.exe
Run Code Online (Sandbox Code Playgroud)
这是我得到的错误:
C:\Users\SCHIER~1\AppData\Local\Temp\ccNPDxb6.o:expression.cpp:(.text+0x0): multiple definition of `OP::getSymbol(unsigned char const&)'
C:\Users\SCHIER~1\AppData\Local\Temp\cc6W7Cpm.o:main.cpp:(.text+0x0): first defined here
collect2.exe: error: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)
问题是,它似乎解析expression.h了两次。如果我只是使用main.cppOR编译它,expression.cpp我就不会收到错误消息。编译器只是忽略我的 #ifndef 并继续......
有什么线索吗?