运算符重载解决方案

时间:2016-11-21 09:32:44

标签: c++ visual-studio pointers operator-overloading

我已经制作了一个c ++代码。保存项目的MList。我重载了<<运算符以特定格式打印MList中的值。这是代码:

name<-c("Dr. T. (Tom) Bailey (m), UCL- Physics" , "Dr. B.K. (Barbara) Blue (f), Oxford - Political Science")
res <- sub(".*\\)\\s+(.*)\\s+\\([mf]\\).*", "\\1", name)
res
## => [1] "Bailey" "Blue"  

但它没有打印正确的值。它打印正确的大小和容量,但不打印值。而不是价值,它打印出一些像心脏的迹象:

Here is the output.

您可以看到它正确打印尺寸和容量但不是值。这是相关的代码。我现在只执行案例2:

friend ostream& operator<<(ostream &out, const MSet<V> &m)
{
    string s = "";
    s += "Size " + to_string(m.size_) + "\n";//out << m.size() << endl;
    s += "Cap " + to_string(m.capacity_) + "\n"; //out << m.capacity() << endl;
    for (int i = 0; i < m.size_; i++)
    {
        if (i < m.size_ - 1)
            s += m.ary[i].element + ",";//out << m.ary[i].element << ",";
        else
            s += m.ary[i].element;
    }
    //cout << "String : " << s;
    return out << s;
}

1 个答案:

答案 0 :(得分:4)

您正在将值添加到临时字符串中,这可能涉及隐式转换,具体取决于模板类型(此处您的数值已转换为字符)。

只需打印值,不要使用临时字符串:

friend ostream& operator<<(ostream &out, const MSet<V> &m)
{
    out << "Size " << m.size_ << endl;
    out << "Cap " << m.capacity_ << endl;
    for (int i = 0; i < m.size_; i++)
    {
        if (i < m.size_ - 1)
            out << m.ary[i].element << ",";
        else
            out << m.ary[i].element;
    }
    return out;
}