【问题标题】:C++ Pointer with restricted method access具有受限方法访问的 C++ 指针
【发布时间】: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++ 中实现这一点 谢谢

【问题讨论】:

  • 全局命名空间中以下划线开头的名称保留用于实现。您的代码格式不正确。

标签: c++ pointers


【解决方案1】:

使用关键字const

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

这使得成员是恒定的,因此它们不能被修改。这也意味着您只能调用标记为constbalance 成员函数。由于getBalance()没有修改值,所以可以标注const

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

【讨论】:

  • 谢谢,这完美地回答了这个问题。
【解决方案2】:

返回一个'const _balance*'。默认情况下,所有非 const 方法都将被禁止。

【讨论】:

    【解决方案3】:

    回复

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

    嗯,你知道,这就是 const 的全部意义所在。

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

    【讨论】:

      猜你喜欢
      • 2011-08-14
      • 1970-01-01
      • 2011-03-04
      • 1970-01-01
      • 2019-10-03
      • 1970-01-01
      • 2020-04-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多