【发布时间】:2016-10-04 11:35:50
【问题描述】:
在 C++ 中,我希望一个实例方法返回一个对象引用,但是调用者应该只被允许调用以访问相关对象的方法。换句话说,不应允许调用者调整指针所引用对象的状态。 在考虑性能和副本位于某个时间点这一事实时,返回对象的副本并不理想。
请看我的例子:
class _balance {
public:
_balance(int pBalance) // Constructor
{setBalance(pBalance);}
int getBalance()
{return bal;}
void setBalance(int pBalance)
{bal = pBalance;}
private:
int bal;
};
class _account {
public:
_account() // Constructor
{balance = new _balance(100);}
_balance *getAccountBalance()
{return balance;}
private:
_balance *balance;
};
int main() {
// Create an account (with initial balance 100)
_account *myAccount = new _account();
// Get a pointer to the account balance and print the balance
_balance *accountBalance = myAccount->getAccountBalance();
printf("Balance is:%d", accountBalance->getBalance() ); // This should be supported
// Changing the balance should be disallowed. How can this be achieved?
accountBalance->setBalance(200);
printf("Adjusted balance is:%d", accountBalance->getBalance() );
}
结果输出:
有没有办法在 c++ 中实现这一点 谢谢
【问题讨论】:
-
全局命名空间中以下划线开头的名称保留用于实现。您的代码格式不正确。