c++即使 mutator 设置正确,int 访问器也会返回 0
我陷入了一个我觉得很愚蠢的问题,因为它基本上只是 2000 行工作 OOP 脚本中的两行代码。
切入主题 - 我有一个实体类,它提供各种信息(名称、地址、ID)。问题是 - 即使 ID 变异器(设置器)设置了正确的值(使用 cout 和返回值进行测试),访问器始终返回 0。
// ID accessor
int Entity::ID() const {
return _ID;
}
// ID mutator
int& Entity::ID( int newID ) {
if ( newID >= 0 ) {
_ID = newID;
}
return _ID;
}
这是我的类(在 AgencyNetwork::createXXX( 中调用 ID( int ) 方法) )并在每个 toStr() 方法中使用(在每个类的末尾)):
Entity.cpp,AgencyNetwork.cpp,Agent.cpp
已解决: 我忘记在每个operator=中添加ID mutator。感谢所有提供帮助的人:)
I'm stuck at a problem I feel stupid about as it's basically just two lines of code in midst of a 2000 line working OOP script.
Cut to the chase - I have an Entity class which provides various information (name, address, ID). The problem is - even if the ID mutator (setter) sets a proper value (tested with cout and return value), the accessor always returns 0.
// ID accessor
int Entity::ID() const {
return _ID;
}
// ID mutator
int& Entity::ID( int newID ) {
if ( newID >= 0 ) {
_ID = newID;
}
return _ID;
}
Here are my classes (the ID( int ) method is called in AgencyNetwork::createXXX() and is used in every toStr() method (at the end of each class)):
Entity.cpp, AgencyNetwork.cpp, Agent.cpp
SOLVED: I forgot to add the ID mutator in every operator=. Thanks to everyone who helped :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最值得注意的是,
Entity
的赋值运算符被破坏了:Most notably, the assignment operator of
Entity
is broken:没有魔法。有明显的BUG。因此,让我们使用跟踪:跟踪每个“mutator”调用。确保除了通过 mutator 调用之外,没有人可以通过其他方式访问 _ID 字段。还跟踪构造函数、复制构造函数、复制赋值运算符和析构函数调用。
然后运行您的代码并跟踪跟踪日志。
我相信你的情况一切都会变得清楚。
注意:如果您的实现错过了上面提到的一些成员函数,您应该使用仅包含跟踪器调用的主体来定义它们。
您不应该让编译器生成任何隐式成员函数,以确保您可以完全控制您的类,特别是
_ID
字段。There is no magic. There is plain BUG. So, lets use tracing: trace every 'mutator' call. Make sure that nobody can access the _ID field in other way than through the mutator call. Trace constructor, copy constructor, copy assignment operator and destructor calls also.
Then run your code and follow the trace log.
I'm sure everything will become clear in your case.
NOTE: if your implementation misses some of the member functions mentioned above you should to define them with the bodies consisting of tracer call only.
You shouldn't let the compiler to make any implicit member function generation in order to be sure that you've the full control of you class and particularly the
_ID
field.