C++ de 一个奇怪的发现


昨天考试才看出,一个对象可以访问类的私有成员,代码说明:

 1 class X {
 2 public:
 3     X() {}
 4     X(int _size): size(_size) {}
 5     X(X& anotherX) {
 6         size=anotherX.size;
 7     }
 8     void show() {
 9         cout<<size<<endl;
10     }
11 private:
12     int size;
13 };
14 
15 int main() {
16     X x1(100),x2(x1),x3;
17     x3=x2;
18     x3.show();
19     x1.show();
20     return 0;
21 }

 


其中复制构造函数访问了一个同类对象的私有成员。

然后就去网上参考了答案:

一.
封装性是对类外(而不是对象外)的操作来说的。
所以可以在类X中定义了操作本类的另一个对象,
这样的操作是因为,类知道他处理的就是他自己的一个对象
二.
这个函数是在 class X类体里面的,
被认为是在同一个域里,也就是类域。

Standard C++ 98 has mentioned:
"A member of a class can be
--private;
its name can be used only by menbers and friends of the class in which it is declared."

 

p.s.

java也是如此

 1 import java.math.BigInteger;
 2 
 3 public class Add {
 4 
 5     /**
 6      * @param args
 7      */
 8     public static void main(String[] args) {
 9         // TODO Auto-generated method stub
10         BigInteger aBig=new BigInteger("100");
11         aBig=aBig.add(new BigInteger("100"));
12         System.out.println(""+aBig+"\n\n");
13         
14         
15         
16         Add a1=new Add(100);
17         a1.plus(new Add(100)).display().plus(new Add(100)).display();
18         a1.display();
19         /*
20          the output is
21 200
22 
23 
24 here, I am: 200
25 here, I am: 300
26 here, I am: 300
27          */
28     }
29     private int a;
30     public Add(int _a) {
31         a=_a;        
32     }
33     public Add plus(Add another){
34         a+=another.a;
35         return this;        
36     }
37     public Add display() {
38         System.out.println("here, I am: "+a);
39         return this;
40     }
41 }

 

posted on 2013-01-15 18:32  mmqh  阅读(177)  评论(0编辑  收藏  举报

导航