静态成员函数

 1 /* 静态成员函数 */
 2 
 3 #include<iostream>
 4 
 5 using namespace std
 6 
 7 class myclass
 8 {
 9 public:
10     myclass()
11     {
12 
13     }
14 
15     ~myclass()
16     {
17 
18     }
19     
20     void print()
21     {
22         cout << (void*)this << " " << "print" << ebdl;
23     }
24 
25     static intadd(int a,int b)
26     {
27         cout << (void*)this// 静态函数中不能引用this
28         return a+b;
29     }
30 };
31 
32 int main()
33 {
34 
35     // 类成员函数,没有static, &myclass:: 等价于this就知道谁来访问
36     
37     // 静态成员函数谁都可以访问
38 
39     void(myclass::*p1)() = &myclass::print;
40 
41     cout << typeid(&myclass::print).name() << endl;
42 
43     int (*p2)(int a,int b) = &myclass::add;
44 
45     cout << typeid(&myclass::add).name() << endl;
46 
47 
48 
49     cin.get();
50     return 0;
51 }
52 
53 
54 //---------------------------------------------------------
55 
56 
57 // 对于一个类来说,函数都是共享的 即使空指针也可以访问
58 
59 // 函数作为代码  不计入sizeof大小
60 
61 // 对于静态函数而言 无需对象可以引用 对象也可以直接引用
62 
63 // 非静态函数必须要明确对象
64 
65 // 访问类的内部成员变量,内部函数的函数一般设计为普通成员函数
66 
67 // 不访问类的内部成员  内部函数需要设计为静态函数
68 
69 
70 int main()
71 {
72     
73     myclass my1;
74     my1.print();// 必须明确对象
75 
76     myclass *p1 = nullptr;
77     p1->print();
78 
79     cout << myclass::add(10,19) << endl;// 无需对象可以引用
80     
81     cout << my1.add(19,18) << endl;// 对象也可以直接引用
82 
83 
84     cin.get();
85     return 0;
86 }

 

posted on 2015-06-06 15:38  Dragon-wuxl  阅读(128)  评论(0)    收藏  举报

导航