在一行c ++

问题描述

我试图重载运算符“

struct Log
{
    std::string outString;

    template<typename T>
    friend Log& operator<<(Log& log,const T& t)
    {
        std::stringstream temp;
        temp << t;
        std::string str = temp.str();
        log.outString += str;
        if(str == "endl" || str == "\n")
        {
            //end of line -> pass string to custom print function
        }
        return log;
    }
};

在这一行出现了分段错误

log.outString += str;

应该这样称呼。

log << "blub: " << 123 << "endl";

解决方法

您正在比较语句if(t == "endl" || t== "\n")中的整数,将其替换为if(str == "endl" || str == "\n")

这是完整的代码:

#include <iostream>
#include <string>
#include <sstream>

struct Logg
{
    std::string outString;

    template<typename T>
    friend Logg& operator<<(Logg& logg,const T& t)
    {
        std::stringstream temp;
        temp << t;
        std::string str = temp.str();
        logg.outString += str;
        if(str == "endl" || str == "\n")
        {
            //end of line -> pass string to custom print function
        }
        return logg;
    }
};

int main()
{
    struct Logg logg;
    logg << "blub: " << 123 << "endl";
    std::cout << logg.outString << std::endl;

    return 0;
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...