簡體   English   中英

當一個class繼承了一個引用私有屬性的公有方法時會發生什么?

[英]What will happen when a class inherits a public method with reference to private properties?

我為warrior class 定義了私有屬性hpatk ,並假設它們不會被派生類繼承。

然而,在下面的代碼中,派生的 class knight繼承了調用私有屬性atk的公共方法attack 在這種情況下,knight.attack() 仍然正常運行並且似乎可以訪問私有屬性atk ,盡管它不應該由派生 class 繼承。

我對此感到困惑。 你能幫我解釋一下幕后的機制嗎? 當我創建knight class 的實例時,它是否具有atk屬性?

#include <cstdio>
class warrior{
    private:
        int hp,atk;
    public:
        void attack(int &enemyHP) {
            enemyHP -= this->atk;
            printf("Deal %d damage to the enemy.\n", this->atk);
            this->atk += 10;
        }
        warrior(int hp=100, int atk=20) {
            this->hp = hp; this->atk = atk;
        }
};
class knight:public warrior{
    public:
        knight(int hp=200, int atk=50) {}
};
int main()
{
    int enemyHP=100;
    knight Tom = knight();
    Tom.attack(enemyHP); // Deal 20 damage to the enemy.
    Tom.attack(enemyHP); // Deal 30 damage to the enemy.
}

當我創建騎士 class 的實例時,它是否具有 atk 屬性?

是的,它確實。 但是只有繼承自warrior的方法才能訪問它。 private的目標是限制對定義它的 class 的可見性,但它仍然存在於子類中,他們只是無法訪問它(不是沒有訴諸未定義的行為廢話,比如無論如何訪問實例的原始字節). 但是由於knightwarrior ,當它使用warrior行為( warrior本身定義的方法)時,他們可以看到atk就好了。

這可以; atk不是knight公共界面的一部分,但attack是,要使attack起作用,它需要查看warrioratk 通過從直接訪問中隱藏warrioratk ,你已經做了足夠的事情來確保knight可以聲明它自己的atk成員(這將 100% 獨立於warrioratk ,如果也聲明為private ,則只能從定義的方法訪問knight )。 無論如何,它做了它應該做的:

  1. 公共方法在繼承時繼續工作,即使它們對私有成員進行操作
  2. 私有屬性不能被任何未定義為自己的一部分的東西訪問 class (除非通過friend訪問)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM