gpt4 book ai didi

c++ - 如何正确重载 ostream 的 << 运算符?

转载 作者:IT老高 更新时间:2023-10-28 11:26:27 24 4
gpt4 key购买 nike

我正在用 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);
}
}

以及“实现”:

using namespace Math;

std::ostream& Matrix::operator <<(std::ostream& stream, const Matrix& matrix) {

[...]

}

这是编译器给出的错误:

matrix.cpp:459: error: 'std::ostream& Math::Matrix::operator<<(std::ostream&, const Math::Matrix&)' must take exactly one argument

我对这个错误有点困惑,但是在这 6 个月里做了很多 Java 之后,我的 C++ 又变得有点生疏了。 :-)

最佳答案

只是告诉你另一种可能性:我喜欢为此使用 friend 定义:

namespace Math
{
class Matrix
{
public:

[...]

friend std::ostream& operator<< (std::ostream& stream, const Matrix& matrix) {
[...]
}
};
}

该函数将自动定位到周围的命名空间Math (即使它的定义出现在该类的范围内)但不会可见,除非您使用 Matrix 对象调用 operator<< ,这将使参数相关的查找找到该运算符定义。这有时可以帮助模棱两可的调用,因为它对于 Matrix 以外的参数类型是不可见的。在编写其定义时,您还可以直接引用 Matrix 中定义的名称和 Matrix 本身,而不用一些可能很长的前缀来限定名称并提供模板参数,如 Math::Matrix<TypeA, N> .

关于c++ - 如何正确重载 ostream 的 << 运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/476272/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com