我需要从成员函数访问本地对象的私有成员。我认为这个例子更好地解释了它。有没有办法在不公开 *a 或不提供专门分配给 *a 的函数的情况下做到这一点?此 operator+ 函数可能必须多次为本地对象分配和/或取消分配 *a。
这篇文章似乎表明这应该可行。
// object.h
class object {
char *a;
...
}
// object.cpp
object object::operator+(object const &rhs) const {
int amount = ...
object local();
// this is ok
this->a = new char[amount];
// this is ok too
rhs.a = new char[amount];
// this is not
local.a = new char[amount];
....
}
我的编译错误(g++ 4.6.3)是:
error: request for member ‘a’ in ‘local’, which is of non-class type ‘object()’