Sam*_*bot 0 c++ overloading operator-keyword
我只是有一个简单的问题:如何重载+ =运算符以返回一个字符串.这是我尝试过的,但没有成功.
// 'Student' is the class that this function is in
// 'get_name()' returns the name of the student
// 'get_grade()' returns the grade of the student
// Description:
// Ultimately I will be creating a list of students and their grades in
// the format of (Student1, Grade1) (Student2, Name2) ... (StudentN, GradeN)
// in a higher level class, and thus I need an overloaded += function.
Student& Student::operator+=(const Student& RHS)
{
string temp_string;
temp_string = "( " + RHS.get_name() + ", " + RHS.get_grade() + ") ";
return temp_string;
}
Run Code Online (Sandbox Code Playgroud)
纯技术:
// v NO reference here!
std::string Student::operator+=(const Student& rhs)
{
string temp_string;
temp_string = "( " + rhs.get_name() + ", " + rhs.get_grade() + ") ";
return temp_string;
}
Run Code Online (Sandbox Code Playgroud)
但:
这是什么意思?首先,一般两个学生的总和结果是什么?另一个学生?你会如何解释人类语言?开始让人困惑.然后看看以下内容:
int x = 10;
x += 12;
Run Code Online (Sandbox Code Playgroud)
您希望x之后保持值22.特别是:x被修改(除非您添加零...).相比之下,您的操作员不会this以任何方式进行修改- 它甚至没有看到......您如何解释this 现在添加另一名学生?特别是:有一个操作员+接受两个学生,你可以返回某种对或家庭,但用+ =,改变结果类型??? 如果x += 7没有修改x,但返回了一个双?你看到这一切有多混乱吗?
另一方面,我可以想象,你实际上是在寻找显式的强制转换运算符:
operator std::string()
{
std::string temp_string;
temp_string = "( " + this->get_name() + ", " + this->get_grade() + ") ";
return temp_string;
}
Run Code Online (Sandbox Code Playgroud)
这样,您可以将学生添加到字符串中,例如:
Student s;
std::string str;
str += s;
Run Code Online (Sandbox Code Playgroud)
或者您想将学生传递给输出流?然后这个:
std::ostream& operator<<(std::ostream& stream, Student const& s)
{
stream << "( " << s.get_name() << ", " << s.get_grade() << ") ";
return stream;
}
Run Code Online (Sandbox Code Playgroud)
在上面,您可以将强制转换运算符减少为:
operator std::string()
{
std::ostringstream s;
s << *this;
return s.str();
}
Run Code Online (Sandbox Code Playgroud)
甚至可以有一个班轮:
operator std::string()
{
return static_cast < std::ostringstream& >(std::ostringstream() << *this).str();
}
Run Code Online (Sandbox Code Playgroud)
好吧,承认,如果它真的更好,这种演员必要是有争议的......