class MyClass {
int value_;
public:
int& getValueRef() { return value_; } // 返回引用
const int& getValueRef() const { return value_; }
};
int main() {
MyClass obj;
int& ref = obj.getValueRef();
ref = 42; // 修改私有成員 value_
}
是的,主函數中透過引用修改會直接改變私有成員變量。
ref 與 value_ 綁定同一記憶體地址。operator[] 返回引用支援 arr[i] = x;operator* 迭代器解引用。Instance()。return *this 支援鏈式調用 obj.setA(1).setB(2)。int getValue() const) 或 **const 引用** (const int& getValue() const)。setValue(int v),內部可加驗證、通知觀察者、記錄審計日誌。