أرجو من الإخوة الأعضاء إيجاد الخطأ في هذا البرنامج.
المشكلة ببساطة في عملية overloading للـ >> الخاصة بالإخراج
هذا هو الـ header file
// This is the header file for class Array
static const size_t MAX_ITEMS = 100;
#ifndef ARRAY_H
#define ARRAY_H
#include <stdlib.h>
#include <iostream>
using namespace std;
class Array
{
public:
// static const size_t MAX_ITEMS = 100;
Array(); // default constructor
size_t get_num_items() {return num_items;}
int get_item(const size_t item_index);
friend istream& operator >> (istream& ins, Array& new_array);
// precondition: new_array is a valid Array object.
// postcondition: new_array has been filled with data entered
// by the user.
friend ostream& operator << (ostream outs,const Array& new_array);
friend Array operator+ (const Array& A, const Array& B);
friend Array operator- (const Array& A, const Array& B);
friend Array operator* (const Array& A, const Array& B);
private:
size_t num_items;
int array[MAX_ITEMS];
}; // end Array class
#endifو هنا جزء من الـ implementation file و هو سبب المشكلة
istream& operator >> (istream& ins, Array& new_array)
// precondition: new_array is a valid Array object.
// postcondition: new_array has been filled with data entered
// by the user.
{
size_t num_elements = 0;
cout << "How many elements will you be entering for this array?";
ins >> num_elements;
for (size_t i=0; i < num_elements; i++)
{
cout << "Enter next element: ";
ins >> new_array.array;
}
new_array.num_items = num_elements;
return ins;
} // end friend istream& operator >>
ostream& operator <<(ostream& outs, const Array& new_array)
{
outs<<endl<<"the Array elements are : "<<endl;
for (size_t i=0; i<new_array.num_items; i++)
{
outs<<endl<<new_array.array;
}
return outs;
}أرفقت الجزء الخاص بالـ<< مع أنها سليمة و يقبلها الـ compiler بلا مشاكل.
المشكلة هي أن هذه الدالة عبارة عن friend function و المفترض أن لها صلاحية الدخول على الـ member data
و لكن هذه رسالة الـ compiler
array.cpp(71) : error C2248: 'num_items' : cannot access private member declared in class 'Array' array.h(38) : see declaration of 'num_items' array.cpp(74) : error C2248: 'array' : cannot access private member declared in class 'Array' array.h(39) : see declaration of 'array'
أسطر الأخطاء هي
for (size_t i=0; i<new_array.num_items; i++)
و
outs<<endl<<new_array.array;
و هما داخل ال friend function الخاصة بالـoverloading
لماذا لا يحق لها الحصول على قيم لـ private member date
ألا يحق للـ friend functions الحصول على قيم member data حتى ولو كانت private