【问题标题】:concating multiple strings in one line c++在一行中连接多个字符串c ++
【发布时间】:2020-10-30 15:53:03
【问题描述】:

我试图重载运算符“

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(str == "endl" || str == "\n")替换if(t == "endl" || t== "\n")
  • 我建议对"endl" 使用比字符串更健壮的东西,因为编译器没有机会帮助您解决拼写错误。例如一个枚举

标签: c++ string operator-overloading stringstream


【解决方案1】:

您正在比较语句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;
}

【讨论】:

  • 谢谢。我修好了它。但这与我的段错误无关,当我尝试访问 log.outString 时。
  • 你在更正后仍然出现分段错误?
  • 是的,我认为参数顺序是错误的。我无法访问此引用参数的成员变量。
  • 我的代码版本中没有出现任何段错误。检查更新的答案。
猜你喜欢
  • 1970-01-01
  • 2010-10-14
  • 2014-03-15
  • 2012-02-02
  • 2015-09-18
  • 2011-11-06
  • 1970-01-01
  • 1970-01-01
  • 2016-10-13
相关资源
最近更新 更多