【发布时间】:2011-11-24 13:23:21
【问题描述】:
考虑以下代码:
#include <iostream>
#include <map>
class Value
{
public:
void set(const int intValue){ intValue_ = intValue; }
int read() const { return intValue_; }
void replaceIfInMap(){
std::map<int,int>::iterator it;
it = valuesToReplace_->find(intValue_);
if(it != valuesToReplace_->end()){
intValue_ = it->second;
}
}
Value(std::map<int,int>* valuesToReplace) : valuesToReplace_(valuesToReplace){}
private:
std::map<int,int>* valuesToReplace_;
int intValue_;
};
class Holder {
public:
void doStuffWithValues(){
Value a(&valuesToReplace_), b(&valuesToReplace_), c(&valuesToReplace_);
a.set(1); b.set(2); c.set(3);
valuesToReplace[2]=5;
a.replaceIfInMap(); b.replaceIfInMap(); c.replaceIfInMap();
std::cout << "a: " << a.read()
<< " b: " << b.read()
<< " c: " << c.read() << std::endl;
}
private:
std::map<int,int> valuesToReplace_;
};
int main()
{
Holder holder;
holder.doStuffWithValues();
}
我怎样才能以更方便(最好更优雅)的方式访问valuesToReplace_ 成员?我曾考虑将地图存储为Value 类的公共静态成员,但这将否认拥有Holder 类的多个实例的可能性,因为每个Holder 实例都需要一组具有不同替换的Value 实例设置。
全球地图将是一个更丑陋的“解决方案”......
从Holder 调用Value::read() 并进行地图交互没有选项,因为此代码只是一个简化,在实际代码中,每个Value 实例的等价物可以存储指向其他实例的指针同一类使上述方法过于复杂和庞大。
为什么上面的代码甚至可以工作? Holder::valuesToReplace_ 是私人的!这只是正常的 C++ 行为(因为无论如何如果不访问类的私有成员就无法获得该指针)?
【问题讨论】:
-
这个助手类真的有必要吗?看起来你所做的一切可以概括为:
int replace_maybe(int n) { auto it = m.find(n); return it != m.end() ? it->second : n; }