Class C++
Mar 11, 2018 at 12:05am UTC
Question: Your class should have functions called void setvalue(int index) and
int getvalue(int index) that allow you to set and get the value in the array
at a given index.
- I am not sure how to implement this one.. Can anyone please help me, thank you.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
class MyArray {
private :
int N;
int * ptr;
public :
// default constructor
MyArray() {
ptr = NULL;
N = 0;
// deletes the array pointed to by "ptr"
delete [] ptr;
}
// initialisation constructor
MyArray(int n) {
N = n;
ptr = new int [N]; // dynamic memory allocation
}
// destructor
~MyArray() {
delete ptr; // memory is released
}
// member functions
int getVal(int i) {
;
}
void setVal(int i) {
;
}
Mar 11, 2018 at 12:07am UTC
- I tried this, but i believe that it is not the way to do it.
1 2 3 4 5 6 7
int getVal(int i) {
return ptr[i];
}
void setVal(int i) {
ptr[i];
}
Mar 11, 2018 at 3:13am UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
#include <cstddef>
class MyArray {
private :
// default member initialisers
// http://www.stroustrup.com/C++11FAQ.html#member-init
std::size_t size = 0 ;
int * ptr = nullptr ;
public :
MyArray() = default ; // initialise using default member initialisers
// http://en.cppreference.com/w/cpp/language/initializer_list
MyArray( std::size_t n ) : size(n), ptr( new int [size]{} ) {} ;
~MyArray() { delete [] ptr ; } // *** note: delete[]
// http://www.stroustrup.com/C++11FAQ.html#default
MyArray( const MyArray& ) = delete ; // non-copyable
MyArray& operator = ( const MyArray& ) = delete ; // non-assignable
int getVal( std::size_t pos ) const {
if ( pos < size ) return ptr[pos] ;
else /* error: pos is out of bounds */ return 0 ;
}
void setVal( std::size_t pos, int value ) {
if ( pos < size ) ptr[pos] = value ;
else ; // error: pos is out of bounds: do nothing
}
};
Topic archived. No new replies allowed.