有两个类:A 和 B。A 是一个 Sigleton,B 是一个简单的类(例如)。因此,A 类的不同对象之间没有任何关系。
#include <iostream>
using namespace std;
class B {
public:
B(int a, int b) {
this->a = a;
this->b = b;
}
int a, b;
};
class A {//singleton
private:
A(){}
public:
int x, y;
B* b;
static A getInstance() {
static A instance;
return instance;
}
bool operator==(const A& a) {
return a.x == this->x && a.y == this->y;
}
};
void main() {
A* a1 = &A::getInstance();
A* a2 = &A::getInstance();
a1->x = 121;
a1->b = new B(65, 12);
cout << a2->b->a << endl;
system("pause");
}
在这种情况下a1.x=121, a1.y=0, , a1.b.a=65, a1.b.b=12, 并且对象具有a2默认值(a2.x=0, a2.y=0, a2.b=NULL)。发生了什么?!