Description
实现类Elements 和 MyVector中的成员函数,完善这两个类。注意,只要提交类的实现,不需要提交类的声明。
class Elements{
private:
int value;
static int numberOfObjects;
public:
Elements();
Elements(const int &value);//set value
Elements(const Elements &elem);copy constructor
~Elements();//descructor
Elements & operator=(const Elements &elem);//assignment
Elements & operator=(const int &value);//assignment
friend istream& operator>>(istream& is, Elements & elem);
//input one integer, and set the value
friend ostream& operator<<(ostream& os, const Elements & elem);
//output one integer to ostream
void setValue(const int &value);
//set value
int getValue()const;
//get value
Elements & operator+=(const Elements &elem);
Elements & operator+=(const int &value);
Elements operator+(const Elements &elem)const;
Elements operator+(const int &value)const;
bool operator ==(const Elements &elem)const;
bool operator ==(const int &value)const;
bool operator <(const Elements &elem)const;
bool operator <(const int &value)const;
operator int()const;//converts Elementes to int
static int getNumberOfObjects();//return the number of objects
};
class MyVector{
private:
Elements *elem;
int _size;
public:
MyVector();//default constructor
MyVector(int n);// constructor an Array of n Elements
MyVector(const MyVector &vec);//copy constructor
~MyVector();//destructor
const MyVector & operator=(const MyVector &vec);//assignment
Elements &operator[](int i);//return the references of elem[i]
Elements operator[](int i) const; //return the copy of elem[i]
int size()const;//return the size
bool operator == (const MyVector &vec)const;//judge if it is equal
friend istream& operator>>(istream& is, MyVector & vec);
//first input n as a _size, then input elem[0],elem[1],…,elem[n-1];
friend ostream& operator<<(ostream& os, const MyVector & vec);
//output elem[0],elem[1],elem[2],..,elem[_size-1] in a line, separated by a
//space. e.g _size = 2 and elem[0]=5,elem[1]=6, you should output
//”5 6” in a line
};
Sample Input
Copy sample input to clipboard
2
1 3
2
2 2
1
Sample Output
1 3
2 3
2 2
2 2
They are equal
Hint
Elements getSum(const MyVector &vec)
{
Elements sum = 0;
for(int i=0;i<vec.size();i++)
{
sum += vec[i];
}
return sum;
}
void sample()
{
MyVector vec;
while( cin >> vec )
{
cout << vec << endl;
MyVector vec2 = vec;
Elements sum = getSum(vec);
int average = (int)sum / vec.size();
for(int i=0;i<vec.size();i++)
{
if( vec[i] < average )
{
vec [i] = average;
}
}
cout << vec << endl;
if( vec == vec2 )
{
cout << "They are equal" << endl;
}
}
}
int main()
{
sample();
if(Elements::getNumberOfObjects()!=0)
{
cout << "Error: occupied memory" << endl;
cout << "Too young too simple, sometimes naive!" << endl;
}
return 0;
}
输入数据保证合法,不用检查异常的情况