Problem C: The first experience of a class (V)Time limit:1 Sec Memory limit:128 MB
submit:433 solved:237
[Submit] [Status] [Web Board]
Description
Defines a class of data, with only one attribute of type int and the following methods:
1. Default constructor, initializes the property to 0 and outputs "Data ' default constructor."
2. destructor, Output: "Data # is erased." Where "#" is the property value.
4. int GetValue ()--Gets the property value.
5. void SetValue (int)--Sets the property value.
Defines an array class DataArray consisting of the objects of data, which includes 1 properties of type int and a data* type of property, representing the number of elements in the array, all elements. Define the following methods:
2. Constructor--parameter format refer to the call method of the main function, output: "DataArray ' s constructor."
3. int Getsum ()--to find the value of all data object properties.
4. destructor--Output line "DataArray ' Deconstructor." Input
A number of integers. Number is greater than 2.
The 1th n represents the number of elements that are entered later. Then there are n integers. They are used to set the array element values of the DataArray object Datas in the main function.
The last integer is used to set the value of the object that TESTP points to in the main function. Output
See Sample ~ sample Input 1 2 3 4 5 6 7 8 9 1222 Sample Output Data ' s default constructor. Data ' s default constructor. Data ' s default constructor. Data ' s default constructor. Data ' s default constructor. Data ' s default constructor. Data ' s default constructor. Data ' s default constructor. Data ' s default constructor. Data ' s default constructor. Data ' s default constructor. DataArray ' s constructor. The Sum is 55Data ' s default constructor. Data 1222 is erased. The Data is erased. Data 9 is erased. Data 8 is erased. Data 7 is erased. Data 6 is erased. Data 5 is erased. Data 4 is erased. Data 3 is erased. Data 2 is erased. Data 1 is erased. DataArray ' s deconstructor. Data 0 is erased. HINT
Append Code append.cc,
#include <iostream> using namespace std;
class data{int i; Public:data () {i=0; cout<< "Data ' s default constructor."
<<endl; } ~data () {cout<< "Data" <<i<< "is erased."
<<endl;
int GetValue () {return i;
} void SetValue (int a) {i=a;
}
};
Class DataArray {Private:data *array;
int count;
Public:dataarray (int n,int *p) {array=new data[n];
for (int j=0;j<n;j++) {array[j].setvalue (p[j]);
} count=n; cout<< "DataArray ' s constructor."
<<endl;
int getsum () {int sum=0;
for (int j=0;j<count;j++) {sum+=array[j].getvalue ();
return sum;
} ~dataarray () {delete []array; cout<< "DataArray ' s deconstructor."
<<endl;
}
};
int main () {int i, n; Data Test,*TESTP;
cin>>n;
int tmp[n];
for (i = 0; i < n; i++) cin>>tmp[i];
DataArray datas (n, TMP);//cout<< "Sum is" <<datas.getsum () <<endl;
TESTP = new Data;
cin>>n;
Testp->setvalue (n);
Delete TESTP;
return 0;
}