这是我想到的最小的示例。 首先是类的头文件。只要使用 << 运算符,该类应该简单地打印它所包含的一个双精度数。
#pragma once
#ifndef EURO_H
#define EURO_H
#include <ostream>
namespace EU
{
class Euro final
{
public:
explicit Euro(double value);
virtual ~Euro() = default;
double getValue() const;
friend std::ostream& operator<<(std::ostream &os, const Euro &euro);
private:
double m_value;
};
}
#endif // EURO_H
现在是 .cpp 文件。
#include "euro.h"
using namespace EU;
Euro::Euro(double value)
{
m_value = value;
}
double Euro::getValue() const
{
return m_value;
}
std::ostream& operator<<(std::ostream &os, const Euro &euro)
{
os << euro.getValue() << "EUR";
return os;
}
最后,是主要代码 main.cpp
#include "euro.h"
#include <iostream>
using namespace EU;
int main()
{
auto e = Euro(3.14);
std::cout << e << std::endl;
}
然而,当我使用以下方式进行编译时:
g++ -std=c++11 *.cpp
出现以下错误:
/tmp/ccP7OKC5.o: In function `main':
main.cpp:(.text+0x35): undefined reference to `EU::operator<<(std::ostream&, EU::Euro const&)'
collect2: error: ld returned 1 exit status
我做错了什么?
祝好, 乔里斯
value
,只需尝试打印一个静态值! - Lightness Races in Orbit#pragma once
和头文件保护#ifndef ... #define .... #endif
。 - Francis Cugler