2016-10-31 13 views
0

私はちょうど質問があります:どのように+ =演算子をオーバーロードして文字列を返すことができますか?ここで私が試したことはありますが、成功はありません。+ =演算子をオーバーロードして文字列を返す方法は?

技術的に
// '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; 
} 
+4

戻り値の型を 'std :: string'に変更しますか? – NathanOliver

+2

@ NathanOliverどのようにそのアイデアを考え出しましたか? o_o – DeiDei

+2

これは混乱して予想外になることに注意してください。現在のオブジェクトを変更していないようです。私はこれをしないことを非常に提案します。 – Falmarri

答えて

7

ピュア:

// 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; 
} 

しかし:

この意味するものは何?まず、一般的に2人の学生の合計の結果はどうなりますか?もう一人の学生?それを人間の言葉でどのように解釈しますか?すでに混乱し始めている。その後、次のを見て:

int x = 10; 
x += 12; 

あなたはxは、その後、特に値22を保持するために期待する:(あなたがゼロを追加しない限り、...)xが変更されました。対照的に、あなたのオペレータはthisを変更することはありません。それは見ていません... thisに今他の学生を追加するとどう解釈しますか?特に:演算子+ 2人の生徒を受け入れると、何らかの種類のペアやファミリーを返すことができましたが、+ =で結果の型を変更しました??? x += 7がxを修正しなかったが、二重を返すとどうなるでしょうか?あなたはこれがどれほど混乱しているかを見ていますか?

operator std::string() 
{ 
    std::string temp_string; 
    temp_string = "(" + this->get_name() + ", " + this->get_grade() + ") "; 
    return temp_string; 
} 

をこの方法で、あなたは文字列、Eに学生を追加することができます。

一方、私はあなたが実際に代わり、明示的なキャスト演算子を探していること、しかし、想像できます。 g。

Student s; 
std::string str; 
str += s; 

あなたは出力ストリームに渡しますか?そして、この:それは1つのライナー持つことも可能です

operator std::string() 
{ 
    std::ostringstream s; 
    s << *this; 
    return s.str(); 
} 

:上記で

std::ostream& operator<<(std::ostream& stream, Student const& s) 
{ 
    stream << "(" << s.get_name() << ", " << s.get_grade() << ") "; 
    return stream; 
} 

、あなたがキャスト演算子を減らすことができることがあれば

operator std::string() 
{ 
    return static_cast < std::ostringstream& >(std::ostringstream() << *this).str(); 
} 

まあが、入院このキャストに必要なものは本当にきれいです...

+0

あなたのご意見ありがとうございます、本当にありがとうございます:)私はあなたが言っていることを見ていきます(確かに、私はオーバーロードをよくしていないので、あなたの説明が本当に助けになりました)。 –

+0

だから実装しました: 演算子std :: string() { std :: string temp_string; temp_string = "(" + this-> get_name()+ "、" + this-> get_grade()+ ")"; return temp_string; } これは完全に動作しますが、get_gradeはfloatを返します。このコンテキスト内でこれを文字列に変換する方法はありますか? ありがとう! –

+1

@SamTalbot 'std :: to_string'? – immibis

関連する問題