如何正确地重载<<操作员为ostream? [英] How to properly overload the << operator for an ostream?

查看:137
本文介绍了如何正确地重载<<操作员为ostream?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C ++中为矩阵操作编写了一个小矩阵库。但是我的编译器抱怨,之前它没有。这个代码留在货架上6个月,在我将我的计算机从debian蚀刻升级到lenny(g ++(Debian 4.3.2-1.1)4.3.2
)然而我在Ubuntu系统上有同样的问题具有相同的g ++。

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);
    }
}

b
$ b

And the "implementation":

using namespace Math;

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

    [...]

}

这是编译器给出的错误:

This is the error given by the compiler:


matrix.cpp:459:error:'std :: ostream&
Math :: Matrix :: operator<<(std :: ostream& amp;
const Math :: Matrix&)必须接受
一个参数

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

我对这个错误感到困惑,但是我的C ++在这6个月之后做了大量的Java之后又有点生锈了。 : - )

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.

这篇关于如何正确地重载&lt;&lt;操作员为ostream?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆