我正在尝试使用+连接字符串,但是发生了一些奇怪的事情。这是我为课程项目准备的“成绩”课程:
#pragma once
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Grade {
private:
string className;
string student;
string letter;
public:
Grade(string c, string s, string l) : className(c), student(s), letter(l) {}
string getLetterGrade() const { return letter; }
string getClassName() const { return className; }
string getStudent() const { return student; }
void setLetterGrade(string l) { letter = l; return;}
void setClassName(string c) { className = c; return;}
void setStudnet(string s) { student = s; return;}
string toString() const { string output = "hello"+student; return output; }
};
显然,toString()方法当前不是我想要的。如果按上述方式运行toString(),我将得到“ hello529173860”。但是,如果我将行更改为:
string toString() const { string output = student+"hello"; return output; }
那么输出为“ hello3860”。这不仅是将hello字符串放在最前面,而且还可以在此过程中替换学生字符串中的字符...以某种方式?
此外,如果我尝试使用:
string toString() const { string output = "hello"+" world"; return output; }
我收到一个错误:
Grade.h: In member function ‘std::string Grade::toString() const’:
Grade.h:29:53: error: invalid operands of types ‘const char [6]’ and ‘const char [7]’ to binary ‘operator+’
string toString() const { string output = "hello"+" world"; return output; }
^
我真的对这里发生的事情不知所措...尤其是因为我在程序的前面完成了字符串连接而没有任何问题。我想要的是输出类似:
“学生+ [一些空白] +字母+ [一些空白] + className”
std::string
可以将A添加到任何内容(另一个std::string
,双引号的字符串文字,char
)中,并提供直观的结果,但是如果您尝试将双引号的字符串文字添加到另一个字符串文字中,char
那么它将不会“起作用”:
添加到char
或其他整数值的字符串文字将经过标准转换为const char*
,然后添加到指针的任何数字将沿着该字符数的文字移动:如果偏移量不在字符串文字内,则当您取消引用(使用)结果指针,
即使衰减到两个指针后,也不能添加两个字符串文字,所以您会遇到编译时错误。
有时,您可能希望显式构造一个,std::string
以便与其他值的串联按您的意愿进行工作:例如my_string = std::string("hello ") + my_const_char_ptr + '\n'
。
例子:
std::string s = "Hello";
s + " World"; // ok
"Hello " + s; // ok
"Hello " + "World"; // NOT ok - two string literals
s += " World"; // ok
s += " Goodbye " + "World"; // NOT ok - "+" evaluated before "+="
s += std::string(" Goodbye ") + "World"; // OK - right-hand-side no longer two literals
// BUT may be slower than two "s +="
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句