在C++中,我希望让一个实例方法返回一个对象引用,但是只应该允许调用者访问有关对象的方法。换句话说,调用者不应该被允许调整指针引用的对象的状态。 当考虑到性能以及副本处于某个时间点时,返回该对象的副本并不理想。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++中实现这一 感谢
在全局名称空间中以下划线开头的名称保留用于实现。你的代码不合格。 –