ماذا "لا يمكن تحويل" هذا المؤشر من "constand" إلى "يد &" يعني؟ (C ++)
سؤال
يحدث الخطأ عندما أحاول القيام بذلك
friend std::ostream& operator<<(std::ostream& os, const hand& obj)
{
return obj.show(os, obj);
}
حيث اليد هي فئة قمت بها، وإظهار
std::ostream& hand::show(std::ostream& os, const hand& obj)
{
return os<<obj.display[0]<<obj.display[1]<<obj.display[2]<<obj.display[3]<<obj.display[4];
}
حيث يتم الإعلان عن العرض char display[6]
.
لا أحد يعرف ما يعني الخطأ؟
المحلول
تحتاج إلى جعل hand::show(...)
أ const
طريقة؛ وليس من المنطقي تمرير مرجع OBJ - إنه يتلقى ذلك بالفعل باسم "this
مؤشر.
هذا يجب أن يعمل:
class hand {
public:
std::ostream& show(std::ostream &os) const;
...
};
friend std::ostream& operator<<(std::ostream& os, const hand& obj)
{
return obj.show(os);
}
نصائح أخرى
تحتاج إلى وظيفة نفسها أيضا لتكون CONST (لاحظ "CONS" في نهاية السطر الأول):
std::ostream& hand::show(std::ostream& os, const hand& obj) const
{
return os<<obj.display[0]<<obj.display[1]<<obj.display[2]<<obj.display[3]<<obj.display[4];
}
لا تنتمي إلى StackOverflow