[英]Using getter, setter in c++
我想在C ++中使用具有如下整數數組的類:
class A{
private:
int arr[50];
}
我將從文本文件中讀取這樣的內容:
sum i1 i2
這意味着:數組的總和index1和index2並存儲在index1中。
我怎么能這樣做,使用getter和setter,如:
seti2(geti1()+geti2())
或類似的東西,(因為它不是很有用,我不想為每個索引寫入getter和setter geti1()geti2()... geti50())
你有什么主意嗎?
順便說一句,我的第二個問題是,getter不應該有任何參數,並且setter應該只有一個參數嗎?
一個想法可能是使用實際索引。 所以你有一個get
函數,它以索引作為參數,以及一個set
函數,它將索引和值作為參數。
另一種解決方案是重載operator[]
函數,以提供類似數組的索引。
要使用setter / getter進行封裝,您可以使用,例如:
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));
但是,從文本文件中讀取解析命令將需要更多工作。
如果您仍想利用字段的名稱,可以使用單個getter / setter並使用枚舉來使代碼更有意義:
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);
}
如果您不想手動創建枚舉,並且可以訪問Boost庫,則可以使用BOOST_PP_ENUM_PARAMS
。 或者,您可以使用簡單的shell腳本來生成枚舉。 有關詳細信息,請參閱此stackoverflow問題 。
我可以建議:
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;
}
}
所以你可以;
get(i);
set(i, get(x) + get(y));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.