什么是对象?在int a; 中, a就是对象。那么如何与对象a进行通信呢? 简单啊,且看程序:
- #include <iostream>
- using namespace std;
-
- int a;
-
- int main()
- {
- a = 1; //往对象中写数据
- cout << a << endl; //从对象中读取数据
-
- return 0;
- }
继续上菜,爱吃不吃:
- #include <iostream>
- using namespace std;
-
- class A
- {
- private:
- int x;
- static A *pInstance;
-
- public:
- void set(int m)
- {
- x = m;
- }
-
- int get()
- {
- return x;
- }
-
- static A *getInstance()
- {
- static A* pInstance = NULL;
- if(NULL == pInstance)
- {
- pInstance = new A;
- }
-
- return pInstance;
- }
- };
-
-
- int main()
- {
- A::getInstance()->set(100);
- cout << A::getInstance()->get() << endl;
-
- //A::getInstance()指向一个单例
-
- return 0;
- }
继续上菜:
- #include <iostream>
- using namespace std;
-
- class A
- {
- private:
- int x;
- static A *pInstance;
-
- public:
- void set(int m)
- {
- x = m;
- }
-
- int get()
- {
- return x;
- }
-
- static A *getInstance()
- {
- static A* pInstance = NULL;
- if(NULL == pInstance)
- {
- pInstance = new A;
- }
-
- return pInstance;
- }
- };
-
- class B
- {
- public:
- void fun1()
- {
- A::getInstance()->set(100);
- }
-
- void fun2()
- {
- cout << A::getInstance()->get() << endl;
- }
- };
-
-
- int main()
- {
- B b;
- b.fun1();
- b.fun2();
-
- return 0;
- }
由此可见,对象间的勾搭是通过接口来起作用的,无非就是入和出。