将双点坐标转换为字符串

Convert double point coordinates into string

本文关键字:字符串 转换 坐标      更新时间:2023-10-16
string Point::ToString(const Point& pt)
{
    std::stringstream buffX;  //"Incomplete type is not allowed"????
    buffX << pt.GetX(); // no operator "<<" matches these operands????
    std::stringstream buffY;
    buffY << pt.GetY();
    string temp = "Point(" + buffX + ", " + buffY + ")";  //???....how to combine a couple of strings into one?..
    return temp.str();
}

我遵循了类似问题中的代码,但系统显示"不允许不完整的类型"---buffX 下的红线

"<<"下的红线也表示----没有运算符"<<"与这些操作数匹配

真的不知道为什么..

谢谢!

您需要#include <sstream>才能使用std::ostringstream

然后:

std::string Point::ToString(const Point& pt)
{
    std::ostringstream temp;
    temp << "Point(" << pt.GetX() << ", " << pt.GetY() << ")"; 
    return temp.str();
}

不清楚你为什么要传入一个Point,因为这是该类的成员。也许更清洁的是:

std::string Point::ToString() const
{
    std::ostringstream temp;
    temp << "Point(" << GetX() << ", " << GetY() << ")"; 
    return temp.str();
}

这也许是错误的,假设GetX()GetY() return某种数字类型(intfloatdouble,...(。如果不是这种情况,您可能希望更改它们(最小惊讶原则(或直接访问class的基础数据成员。

如果你正在为这种编译器错误而苦苦挣扎,我强烈建议你给自己一本好C++书。