ماذا "لا يمكن تحويل" هذا المؤشر من "constand" إلى "يد &" يعني؟ (C ++)

StackOverflow https://stackoverflow.com/questions/928662

  •  06-09-2019
  •  | 
  •  

سؤال

يحدث الخطأ عندما أحاول القيام بذلك

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];
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top