0
我需要從成員函數訪問本地對象的私有成員。這個例子更好地解釋了我的想法。有沒有辦法做到這一點,而不需要公開,或者沒有提供專門用於分配* a的功能?這個operator +函數可能不得不在不同時間爲本地對象分配和/或釋放* a。訪問本地對象的私有成員(同一類類型)
這個post似乎暗示這應該工作。
// 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];
....
}
我的編譯錯誤(克++ 4.6.3)是:
error: request for member ‘a’ in ‘local’, which is of non-class type ‘object()’
看起來你想要調用對象的構造函數,對吧?調用默認構造函數時,不需要「()」,只有在將參數傳遞給構造函數時才需要。 – Brady