2016-10-04 37 views
0

在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()); 
    } 

结果输出:

enter image description here

有没有办法在C++中实现这一 感谢

+0

在全局名称空间中以下划线开头的名称保留用于实现。你的代码不合格。 –

回答

0

重新

调用者不应该被允许调整由指针

嗯,你知道,这就是const是所有引用的对象的状态。

你需要一本好的教科书。查看SO C++ textbook FAQ

1

使用关键字const

const _balance* accountBalance = myAccount->getAccountBalance(); 

这使得它成员是恒定的,所以他们不能被修改。这也意味着您只能致电balance标记为const的成员函数。由于getBalance()不修改的值,它可以被标记const

 int getBalance() const // <---- 
      {return bal;} 
+0

谢谢,这完美地回答了这个问题。 –

1

返回一个“常量_balance *”。所有非const方法默认情况下都是不允许的。