使用 cout 中的链接时 C++ ostringstream 奇怪的行为

标签 c++ ostringstream

我是 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<

但是,如果我现在运行程序,第二个 block 被注释掉(我有两个版本的 operator const*,默认情况下第二个被注释掉),它会显示

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

但是在第二个 block 未注释的情况下运行时,输出符合预期:

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

当我在同一行中显示两个 Point 对象时(某种链接,虽然我不知道链接在这里是否正确)似乎会出现此问题

我的问题是,为什么会这样?

更新

我已将 std::ostream& operator << 函数添加到我的 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!

streamoperator const char*() 中声明这将其生命周期限制为该功能。当退出该范围时,它会被销毁。结果,您将返回一个指向不再存在的东西的指针。

关于使用 cout 中的链接时 C++ ostringstream 奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16904919/

相关文章:

C++ 11 std::enable_if 在 Visual C++ 2013 中重载

c++ - ostringstream 在插入输出后为空

c++ - vim 大括号匹配带有大括号的注释

c++ - 为什么 Eclipse 找不到 g++?

c++ - 在 `std::get<I>` 上使用 `std::tuple` 是否保证对于 `I` 的不同值是线程安全的?

c++ - 使用 C++ 成员函数处理采用简单静态函数指针的回调

c++ - 字符串流和多线程

c++ - CRLF 行尾和 ostringstream

c++ - OStringStream 和命名空间问题 C++