【问题标题】:How to overload the << operator?如何重载 << 运算符?
【发布时间】:2015-03-24 14:43:21
【问题描述】:

我正在尝试构建自己的 std::vector 类,但我无法重载下标 ([]) 和 cout &lt;&lt; 运算符。

到目前为止,我已经尝试将&lt;&lt; 运算符定义为类的公共成员,然后在类声明之外编写函数体。

现在我从 iostream 库中得到充满错误的终端页面,我什至不知道从哪里开始查看它们。

我是 C++ 初学者,不习惯 friend 关键字或 template 关键字。我做错了什么?

template<typename T>
class MyVector {
    private:
        T* Array;
    public:
        T& operator[](int b)
        {
            ...
        }

        std::ostream& output(std::ostream& s) const;
};


std::ostream& operator<<(std::ostream& output, MyVector& A)
{
    int i;
    for(i = 0; i < A.GetDimension(); i++)
    {
        output << A[i] << " ";
    }
    output << "\n";
    return output;
};

【问题讨论】:

  • 你不能混用reallocnew
  • 因为我的评论是正确的。如果将指针从new 传递到realloc,则结果未定义。它可能适用于您的编译器,但会在另一个编译器上崩溃。

标签: c++ operator-overloading operator-keyword cout


【解决方案1】:

你所拥有的是对的,你只是忘记了模板声明:

template <typename T>
std::ostream& operator<<(std::ostream& output, MyVector<T>& A)
{
    int i;
    for (i = 0; i < A.GetDimension(); i++)
    {
        output << A[i] << " ";
    }
    output << "\n";
    return output;
};

【讨论】:

  • 应该是这样。我只是在回答他的问题,并没有仔细研究他的代码。还有很多其他地方可以改进,但我认为这超出了问题的范围,我必须马上离开。
【解决方案2】:
template<typename T>
class MyVector{
    ...
    std::ostream& printToStream(std::ostream& output) const {
        int i;
        for (i = 0; i < Dimension; i++) {
            output << Array[i] << " ";
        }
        output << "\n";
        return output;
    }
    ...
};

template<typename T>
std::ostream& operator<<(std::ostream& output, const MyVector<T>& A) {
   return A.printToStream(output);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-29
    • 2011-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多