这是我的计划:将通过引用传递的两个字符转换为字符串?
#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.此外,我必须感谢您的全力帮助。我还是新手编程,我非常感谢。
这取决于你没有显示的'Example'的细节。 – juanchopanza 2013-03-19 09:51:18
ünead显示如何单个'示例'字符或字符串 –
2013-03-19 09:56:23
@ Cheersandhth.-Alf Eye希望在空间中使用坏咒语? – 2013-03-19 09:59:38