无法让我的重载插入运算符工作

时间:2018-03-27 08:11:29

标签: c++

这是我的主要功能

int main()
{
    const string filename = "ass10data.txt";   // use your filename here
    ifstream fin(filename.c_str());
    if (!fin)
    {
        cerr << "Unable to open " << filename << endl;
        exit(1);
    }
    string buffer;
    Quadrilateral* ptrQuad;
    while (getline(fin,buffer))
    {
        // Process only valid input
        if (buffer.size() > 1)
        {
            ptrQuad = createQuadrilateralFromString(buffer);
            cout << *ptrQuad << endl;
            delete ptrQuad;
        }
    }
    fin.close();
}

这是重载的插入运算符

ostream& operator<<(ostream&out, Quadrilateral *pointerQuad)
{
    if (pointerQuad->getType() == "rectangle")
    {
        out << "Rectangle: sides " << pointerQuad->getFirst() << " and " << pointerQuad->getSecond() << " area=" << pointerQuad->area();
        out << " perimeter=" << pointerQuad->perimeter();
        return out;
    }
    else if(pointerQuad->getType() == "square")
    {
        out << "Square: side "<< pointerQuad->getFirst() << " area="<< pointerQuad->area();
        out << " perimeter=" << pointerQuad->perimeter();
        return out;
    }
    else if(pointerQuad->getType() == "parallelogram")
    {
        out << "Parallelogram: sides " << pointerQuad->getFirst() << " and " << pointerQuad->getSecond() << " area=" << pointerQuad->area();
        out << " perimeter=" << pointerQuad->perimeter();
        return out;
    }
    else if(pointerQuad->getType() == "rhombus")
    {
        out << "Rhombus: side "<< pointerQuad->getFirst() << " area="<< pointerQuad->area();
        out << " perimeter=" << pointerQuad->perimeter();
        return out;
    }
    else
        return out;
}

我收到一条错误消息,提示&#34;不匹配&#39;运营商&lt;&lt;&lt;&#39; (操作数类型是&#39; std :: ostream {aka std :: basic_ostream}&#39;&#39; Quadrilateral&#39;)&#34;我无法弄清楚原因。

1 个答案:

答案 0 :(得分:0)

插入运算符应该对Quadrilateral采用const引用,而不是指向它的指针:

ostream& operator<<(ostream&out, Quadrilateral const &pointerQuad)

当然,这意味着你的函数应该使用值语法,而不是指针。

if (pointerQuad.getType() == "rectangle")
{
    out << "Rectangle: sides " << pointerQuad.getFirst() << " and " << pointerQuad.getSecond() << " area=" << pointerQuad.area();
    out << " perimeter=" << pointerQuad.perimeter();
    return out;
}
[...]