具有受限方法访问的C ++指针

时间:2016-10-04 03:28:12

标签: c++ pointers

在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 ++中实现这一点 感谢

3 个答案:

答案 0 :(得分:1)

使用关键字const

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

这使得成员保持不变,因此无法修改它们。这也意味着您只能调用标记为balance的{​​{1}}成员函数。由于const不会修改该值,因此可以将其标记为getBalance()

const

答案 1 :(得分:1)

返回'const _balance *'。默认情况下,不允许使用所有非const方法。

答案 2 :(得分:0)

RE

  

不应允许调用者调整指针引用的对象的状态

嗯,你知道,这就是const的全部内容。

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