这是我能想到的最小的包含示例。 首先是班级的标题。只要使用< <运算符,此类应该只打印它包含的一倍。如何超载运算符<<从命名空间内
#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',只是[尝试]打印一个静态值! –
作为一个提示,你不需要'#pragma once'和标头守卫#ifndef ... #define ....#endif' –