1

次のクラスがあるとします。

class Test
{
             int num;
     public:
             Test(int x):num(x){}
             Test(const Test &rhs):num(rhs.num+1){}
};

int main()
{
      Test test(10);
      Test copy = test;
}

コピー内のnumは である必要が11あり、私の質問はコピー コンストラクター内に関するものです。コピー内のを初期化するためにusingのプライベート メンバーnumにアクセスできるのはなぜですか? 私を混乱させているのは、 と入力すると、 private にアクセスしようとしているため、もちろん間違っていますが、コピーコンストラクターへの参照によってテストに合格した場合、それは機能します。 testnumnumcout<<test.num<<endlnum

4

3 に答える 3

6

プライベートメンバーは、クラスのインスタンスではなく、クラス自体に対してプライベートです。

于 2012-08-30T03:01:55.257 に答える
3

アクセス制限は、オブジェクトごとではなく、クラスごとです。

「プライベート」とは、同じクラス内からのみアクセスできることを意味します。

「保護された」とは、同じクラス内からアクセスでき、派生クラス内からもアクセスできることを意味します(派生クラスでは、保護された非静的メンバーは、派生クラスタイプの変数を介してのみアクセスできます)。

「パブリック」とは、何からでもアクセスできることを意味します。

アクセス制限のポイントは、コードによる値の使用を停止するのではなく、値が使用されている場所を理解するために検査する必要のあるコードの領域を制限することです。

于 2012-08-30T03:02:21.177 に答える
1

private doesn't mean private to the object instance. It means private to that class. An instance of a class T can access private members of other instances T. Similarly, a static method in a class T can access private members of instances of T.

If private restricted access to only the individual instance, it would make objects non-copyable, since as you pointed out, the copy constructor would not be able to read data from the original instance.

于 2012-08-30T03:04:52.057 に答える