鉴于此代码示例:
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) 这个问题建立在这两个 stackoverflow 帖子的基础上:
问题是:为什么类/结构/枚举不会出现多重定义错误?为什么它只适用于函数或变量?
我写了一些示例代码来试图解决我的困惑。有 4 个文件:namespace.h、test.h、test.cpp 和 main.cpp。第一个文件包含在 test.cpp 和 main.cpp 中,如果取消注释正确的行,则会导致多重定义错误。
// namespace.h
#ifndef NAMESPACE_H
#define NAMESPACE_H
namespace NamespaceTest {
// 1. Function in namespace: must be declaration, not defintion
int test(); // GOOD
// int test() { // BAD
// return 5;
//}
// 2. Classes can live in header file with full implementation
// But if the function is defined outside of the struct, it causes compiler error
struct TestStruct {
int x; …Run Code Online (Sandbox Code Playgroud)