接受C ++字符串和放大器通用类; C形式的字符串 [英] Generic class that accepts C++ string & C style string
本文介绍了接受C ++字符串和放大器通用类; C形式的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以,当你知道了:
C形式的字符串是一个字符数组,与空
So as you know: C style string is a character array that end with "null"
C ++风格的字符串是:
C++ style string is:
string s = "Some text";
因此,要同时接受C ++字符串和C样式的字符串,我是pretty肯定,我必须使用C ++模板。
So to accept both C++ string and C style string, I'm pretty sure I have to use C++ template.
我试图写一个类和一个返回该字符串C ++或C样式字符串的第二个字符的方法。我在正确的轨道上吗?
template <class T>
class mystring {
T pointer;
public:
mystring(T input) { pointer = input }
char getSecondLetter() {
T temp = pointer;
temp++;
return temp;
}
};
int main () {
mystring<I dont know what to put> myobject("HELLO");
cout << myobject.getSecondLetter();
return 0;
}
P.S。不要总是程序员使用T为模板类数据类型?
p.s. Do programmers always use 'T' for template class datatype?
推荐答案
有没有必要,C字符串隐含转换到std :: string的
there is no need, C string implicit convert to std::string
char getSecondLetter( const std::string & s ) {
return s[1];
}
const char *c_str = "hello";
std::string str = "world";
getSecondLetter( c_str ); // e
getSecondLetter( str ); // o
这篇关于接受C ++字符串和放大器通用类; C形式的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文