我正在用C++编写一个小矩阵库来进行矩阵运算.然而,我的编译器抱怨,在它之前没有.这个代码留在架子上6个月,在我之间我将我的计算机从debian etch升级到lenny(g ++(Debian 4.3.2-1.1)4.3.2)然而我在具有相同g ++的Ubuntu系统上遇到了同样的问题.
这是我的矩阵类的相关部分:
namespace Math
{
class Matrix
{
public:
[...]
friend std::ostream& operator<< (std::ostream& stream, const Matrix& matrix);
}
}
Run Code Online (Sandbox Code Playgroud)
而"实施":
using namespace Math;
std::ostream& Matrix::operator <<(std::ostream& stream, const Matrix& matrix) {
[...]
}
Run Code Online (Sandbox Code Playgroud)
这是编译器给出的错误:
matrix.cpp:459:错误:'std :: ostream&Math :: Matrix :: operator <<(std :: ostream&,const Math :: Matrix&)'必须只取一个参数
我对这个错误感到有些困惑,但是在6个月里做了大量的Java后,我的C++又变得有点生疏了.:-)
这基本上就是问题,是否有"正确"的实施方式operator<<?读这个我可以看到类似的东西:
friend bool operator<<(obj const& lhs, obj const& rhs);
Run Code Online (Sandbox Code Playgroud)
喜欢这样的东西
ostream& operator<<(obj const& rhs);
Run Code Online (Sandbox Code Playgroud)
但我不明白为什么要使用其中一个.
我的个人案例是:
friend ostream & operator<<(ostream &os, const Paragraph& p) {
return os << p.to_str();
}
Run Code Online (Sandbox Code Playgroud)
但我可能会这样做:
ostream & operator<<(ostream &os) {
return os << paragraph;
}
Run Code Online (Sandbox Code Playgroud)
我应该根据这个决定做出什么理由?
注意:
Paragraph::to_str = (return paragraph)
Run Code Online (Sandbox Code Playgroud)
其中段落是一个字符串.
可能重复:
非成员运算符重载应放在何处?
在浏览SO时,我经常会发现涉及重载/定义a std::ostream& operator<<(std::ostream& os, const Foo& foo)或a的问题或答案Foo operator+(const Foo& l, const Foo& r).
虽然我知道如何以及何时(不)编写这些操作符,但我对namespace此事感到困惑.
如果我有以下课程:
namespace bar
{
class Foo {};
}
Run Code Online (Sandbox Code Playgroud)
namespace我应该在哪个中编写不同的运算符定义?
// Should it be this
namespace bar
{
std::ostream& operator<<(std::ostream& os, const Foo& foo);
}
// Or this ?
namespace std
{
ostream& operator<<(ostream& os, const bar::Foo& foo);
}
// Or this ?
std::ostream& operator<<(std::ostream& os, const bar::Foo& foo);
Run Code Online (Sandbox Code Playgroud)
同样的问题适用于operator+.那么,这里的好习惯是什么?为什么?