Using getter, setter in C ++

I want to use a class in C ++ that has an integer array as follows:

class A{ private: int arr[50]; } 

I will read something from a text file as follows:

 sum i1 i2 

This means: the sum of the arrays index1 and index2 and storing in index1.

How can I do this using getters and setters, for example:

 seti2(geti1()+geti2()) 

or something like that (because it is not very useful, I do not want to write getter and setter for each index geti1 () geti2 () ... geti50 ())

Do you have any ideas?

By the way, my second question is that getter should not have any parameters, and setter should have only one parameter?

+6
source share
4 answers

One idea might be to use real indexes. So you have one get function that takes an index as an argument and one set function that takes an index and a value as arguments.

Another solution is to overload the operator[] function to provide beautiful array type indexing.

+6
source

To encapsulate using setter / getter, you can use, for example:

 class A{ private: int arr[50]; public: int get(int index); void set(int index, int value); } ... int A::get(int index) { return arr[index]; } void A::set(int index, int value) { arr[index] = value; } .. instanceOfA->set(1, instanceOfA->get(1) + instanceOfA->get(2)); 

However, a parsing command read from a text file will require more work.

0
source

If you still want to use the names of your fields, you can have one getter / setter and use an enumeration to make your code a little more meaningful:

 class A{ public: enum Index { INDEX_SUM, INDEX_I1, INDEX_I2, INDEX_I3, ... INDEX_I50, }; int geti(const Index index); void seti(const Index index, const int value); private: int arr[50]; }; int A::geti(const Index index) { return arr[static_cast<int>(index)]; } void A::seti(const Index index, const int value) { // Maybe don't allow "sum" to be set manually? if (INDEX_SUM == index) throw std::runtime_error("Cannot set sum manually"); arr[static_cast<int>(index)] = value; // Maybe update sum? arr[INDEX_SUM] = std::accumulate(arr, arr + 50, 0); } 

If you do not want to manually create an enumeration and have access to the Boost libraries, you can use BOOST_PP_ENUM_PARAMS . Alternatively, you can use a simple shell script to generate an enumeration. For more on this, see this question on the stack .

0
source

Can i suggest:

 class A{ private: const int ARR_SIZE = 50; int arr[ARR_SIZE]; public: int get(int _iIndex) { return arr[_iIndex]; } void set(int _iIndex, int _iValue) { if (_iIndex < ARR_SIZE) arr[_iIndex] = _iValue; } } 

So you can:

 get(i); set(i, get(x) + get(y)); 
0
source

Source: https://habr.com/ru/post/1011803/


All Articles