如何正确超载 <<ostream 的运算符?
我正在用 C++ 编写一个用于矩阵运算的小型矩阵库.但是我的编译器抱怨,以前没有.这段代码被搁置了 6 个月,在这期间我将我的计算机从 debian etch 升级到 lenny (g++ (Debian 4.3.2-1.1) 4.3.2) 但是我在具有相同 g++ 的 Ubuntu 系统上遇到了同样的问题.
I am writing a small matrix library in C++ for matrix operations. However my compiler complains, where before it did not. This code was left on a shelf for 6 months and in between I upgraded my computer from debian etch to lenny (g++ (Debian 4.3.2-1.1) 4.3.2 ) however I have the same problem on a Ubuntu system with the same g++.
这是我的矩阵类的相关部分:
Here is the relevant part of my matrix class:
namespace Math
{
class Matrix
{
public:
[...]
friend std::ostream& operator<< (std::ostream& stream, const Matrix& matrix);
}
}
以及实施":
using namespace Math;
std::ostream& Matrix::operator <<(std::ostream& stream, const Matrix& matrix) {
[...]
}
这是编译器给出的错误:
This is the error given by the compiler:
matrix.cpp:459: 错误: 'std::ostream&Math::Matrix::operator<<(std::ostream&,const Math::Matrix&)' 必须取正是一个论点
matrix.cpp:459: error: 'std::ostream& Math::Matrix::operator<<(std::ostream&, const Math::Matrix&)' must take exactly one argument
我对这个错误有点困惑,但是在这 6 个月里做了很多 Java 之后,我的 C++ 又变得有点生疏了.:-)
I'm a bit confused by this error, but then again my C++ has gotten a bit rusty after doing lots of Java those 6 months. :-)
推荐答案
您已将您的函数声明为 friend
.它不是班级的成员.您应该从实现中删除 Matrix::
.friend
表示指定的函数(不是类的成员)可以访问私有成员变量.您实现该功能的方式就像 Matrix
类的实例方法,这是错误的.
You have declared your function as friend
. It's not a member of the class. You should remove Matrix::
from the implementation. friend
means that the specified function (which is not a member of the class) can access private member variables. The way you implemented the function is like an instance method for Matrix
class which is wrong.
相关文章