2012-02-02 81 views
-2

由于x_str,y_str是局部的,所以我没有在这个函数中得到正确的输出。 (非法字符打印在x_str和y_str的地方) 我不想将2个更多的成员变量x_str,y_str添加到我的类中。如何打印位置

因此,什么可能是取代这个功能,以获得正确的输出。

string Pos::getPosReport(){ 
     string x_str; 
     x_str = x; 
     string y_str; 
     y_str = y; 
     return string("(" + x_str + "," + y_str + ")"); 
    } 

编辑:

class Pos { 
    int x; 
    int y; 
public: 
    Pos(); 
    Pos(Pos const&); 
    Pos(int,int); 

    Pos&  operator=(Pos const&); 
    bool operator==(Pos const&); 
    bool operator!=(Pos const&); 

    void setPos(Pos const&); 
    void setPos(int,int); 

    void setx(int); 
    void sety(int); 

    int getx() const ; 
    int gety() const ; 

    string getPosReport(); 

    virtual ~Pos(); 
}; 
+1

问题不明确。你需要解决什么问题? – 2012-02-02 14:26:08

+1

谁是x和y? – 2012-02-02 14:26:21

回答

5
std::stringstream ss; 
ss << "(" << x << "," << y << ")"; 
return ss; 

(这是全功能体)。

+0

我的编译器给'std :: stringstream ss; return(ss <<“(”<< x <<“,”<< y <<“))”)。str(); '**错误:'struct std :: basic_ostream '没有名为'str'**的成员,但是'stringstream s; s <<“(”<< x <<“,”<< y <<“)”; return s.str();' 编译正确。感谢您的答复。 – 2012-02-02 14:47:03

+0

这不起作用,因为'operator <<'返回对ostream的引用,而ostream没有'str()'成员函数。 – 2012-02-02 14:48:47

+0

哎呀,我的错。感谢修复,@EAGER_STUDENT。 – 2012-02-02 15:05:00

1

问题不在于x_stry_str是本地变量,而是分配不符合您的期望。那不是你把int转换成string

您可以使用_itoa()int转换为char*stringstream,如在Michael的回答中所述。

+0

int正被转换为char的哪个operator =被定义。该字符串只包含单个字符。 – 2012-02-02 14:46:39

+0

@sftrabbit如果你有int 1,它不会被转换成char''1''。 – 2012-02-02 14:58:27

+0

(这是回应你之前删除的评论:“那是标准吗?”)是的,我相信如此。如果int的值不适合char,则结果将被实现定义。如果实现定义了要被签名的char,那么演员也将被实现定义。 – 2012-02-02 15:03:45