簡體   English   中英

使用cout中的鏈接時C ++ ostringstream奇怪的行為

[英]C++ ostringstream strange behavior when chaining in cout is used

我是C ++初學者(來自Java)。 我有以下代碼:

//#include <boost/algorithm/string.hpp>
#include <iostream>
#include <math.h>
#include <vector>
#include <string.h>
#include <string>
#include <bitset>
#include <algorithm>
#include <sstream>
#include <memory>
#include <assert.h>
#include <cctype>

using namespace std;

class Point{
private:
    int x;
    int y;
public:
    Point(int x,int y){
        this->x=x;
        this->y=y;
    }

    int getX(){
        return x;
    }

    int getY(){
        return y;
    }

    operator const char*(){
        return toString().c_str();
    }

    string toString(){
        ostringstream stream;
        stream<<"( "<<x<<", "<<y<<" )";
        return stream.str();
    }
};


class Line{
private:
    Point p1=Point(0,0);
    Point p2=Point(0,0);

public:
    Line(Point p1, Point p2){
        this->p1=p1;
        this->p2=p2;
    }

    Point getP1(){
        return p1;
    }

    Point getP2(){
        return p2;
    }

    operator const char*(){
        ostringstream stream;
        stream<<"[ "<<p1<<" -> "<<p2<<" ]";
        return stream.str().c_str();
    }

    //    operator const char*(){
    //        ostringstream stream;
    //        stream<<"[ "<<p1<<" -> ";
    //        stream<<p2<<" ]";
    //        return stream.str().c_str();
    //    }
};

int main()
{

    Line line=Line(Point(1,2), Point(3,4));
    cout<<line<<endl;


    cout<<"\nProgram exited successfully."<<endl;
    return 0;
}

我已經重新定義了運算符const *,以便可以使用cout <

但是,如果我按現在的樣子運行程序,第二個代碼塊被注釋掉(我有2個版本的const *操作符,默認情況下第二個代碼被注釋掉),它將顯示

[(1,2)->(1,2)]

但是,當在第二個塊未注釋的情況下運行時,輸出是預期的:

[(1,2)->(3,4)]

當我在同一行中顯示兩個Point對象時,似乎出現了問題(某種形式的鏈接,盡管我不知道這里的鏈接是否正確)

我的問題是,為什么會這樣?

UPDATE

我已經將std :: ostream&運算符<<函數添加到我的Line類中,但是現在我收到以下錯誤:

/home/ryu/qt_workspace/hello/main.cpp:67: error: 'std::ostream& Line::operator<<(std::ostream&, const Line&)' must take exactly one argument

/home/ryu/qt_workspace/hello/main.cpp:77: error: cannot bind 'std::ostream {aka std::basic_ostream<char>}' lvalue to 'std::basic_ostream<char>&&'

問候,奧雷利亞

如果要使用cout << ,則有一種更直接的方法。

將此功能添加到Line

friend std::ostream& operator << ( std::ostream & os, const Line & l ){
    os << "[ " << l.p1 << " -> " << l.p2 << " ]";
    return os;
}

您還應該注意,您的方法正在返回無效的內存-這是Java與C ++不同的重要方式。

    return stream.str().c_str();  // Danger!

stream是在operator const char*()聲明的,它將其生存期限制為該函數。 退出該作用域時將銷毀它。 結果,您將返回一個指針,該指針不再存在。

實際上,我認為使用C ++ 11按值返回字符串是完全可以的,因此您可以在那里進行傳輸,而不是使用下面的cstring。

什么是移動語義?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM