【发布时间】:2011-02-13 05:31:16
【问题描述】:
鉴于此代码示例:
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
complex.cpp:
#include "complex.h"
Complex::Complex(float Real, float Imaginary) {
m_Real = Real;
m_Imaginary = Imaginary;
}
main.cpp:
#include "complex.h"
#include <iostream>
int main()
{
Complex Foo(3.4, 4.5);
std::cout << Foo << "\n";
return 0;
}
编译此代码时,我收到以下错误:
multiple definition of operator<<(std::ostream&, Complex const&)
我发现制作这个函数inline 可以解决问题,但我不明白为什么。为什么编译器会抱怨多重定义?我的头文件受到保护(使用#define COMPLEX_H)。
而且,如果抱怨operator<< 函数,为什么不抱怨public real() 函数,它也在标头中定义?
除了使用inline 关键字之外,还有其他解决方案吗?
【问题讨论】:
-
您也可以将函数设为静态。 inline 说明符通常用于强制函数具有内部链接。
-
@Akanksh,实际上这正是“内联”的用途。
-
@Akanksh:在 C++ 中不推荐使用
static来实现此目的。static已被匿名命名空间完全取代,尽管在这种特殊情况下,inline是要走的路。 -
@Akanksh:这会通过在不同的翻译单元中赋予相同的名称 (
operator<<) 不同的含义来引发 ODR 违规。
标签: c++ header-files