c++ - 将通过引用传递的两个字符转换为字符串?

标签 c++ string character

这是我的程序:

#include <iostream>
#include <string>
using namespace std;

template <class T>
class Example
{
  private:
    T data;

  public:
    Example() { data = 0; }
    void setData(T elem) { data = elem; }

    template <class U>
    friend ostream& operator << (ostream &, const Example<U>&);

    friend ostream& operator << (ostream &, const Example<char>&);

    friend string operator + (const Example<char> &, const Example<char> &);

    template <class U>
    friend U operator + (const Example<U> &, const Example<U> &);
};

template <class U>
U operator + (const Example<U> &a, const Example<U> &b)
{
    U c;
    c = a+b;
    return(c);
}

string operator + (const Example<char> &a, const Example<char> &b)
{
       string a1("");
       a1+=a.data;
       a1+=b.data;
       return(a1);

}

template <class T>
ostream& operator << (ostream &o, const Example<T> &t)
    {
      o << t.data;
      return o;
    }


ostream& operator << (ostream &o, const Example<char> &t)
{
  o << "'" << t.data << "'";
  return o;
}



int main()
{
    Example<int> tInt1, tInt2;
    Example<char> tChar1, tChar2;

    tInt1.setData(15);
    tInt2.setData(30);

    tChar1.setData('A');
    tChar2.setData('B');

    cout << tInt1 << " + " << tInt2 << " = " << (tInt1 + tInt2) << endl;
    cout << tChar1 << " + " << tChar2 << " = " << (tChar1 + tChar2) << endl;
    return 0;
}

如何将这两个字符变成一个可以返回的字符串?我尝试了多种方法,但似乎无法使它们中的任何一种起作用。我认为这可能与通过引用传递的字符有关。

编辑: 好的,所以我可以毫无问题地使用该特定功能。现在我编译了它,但在显示任何内容之前,出现了段错误。 U 数据类型的添加有问题。它会添加 A 和 B 并返回 AB,但它不会添加 15 和 30。另外,我不得不说谢谢你的所有帮助。我对编程还是个新手,我真的很感激。

最佳答案

#include <sstream>

string operator + (const Example<char> &a, const Example<char> &b) {
    std::ostringstream sstream;
    sstream << a << b;
    return sstream.str();
}

关于c++ - 将通过引用传递的两个字符转换为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15496089/

相关文章:

java - 排序时遇到问题

javascript - 在javascript中连接正则表达式时重复

android - AndEngine 自定义 Sprite

java - 在 Java 中使用 .substring 操作字符串

c++ - 如果配置中未使用字段,则修复警告 "field a is not used"的好方法

c++ - 为什么进程会在 RtlExitUserProcess/LdrpDrainWorkQueue 中挂起?

html - 让 HTML 识别\n 和\t

search - 如何在 Google 中搜索代码和其他与编程相关的关键字?好像去掉了特殊字符

C++如何指向一个数组的成员

python - 从 C++ 转换为 Python - 如何在 Python 中声明没有定义的虚方法