static测试
// static函数一般只为类所拥有,但是我们也可以用类的对象来调用 // static函数,我们不推荐这么做。 // static函数只能访问与读写staitc变量 // 普通函数可以访问与改写static变量 #include <iostream> using namespace std; class staticDemo { int i; static int j; public: staticDemo(int ii) : i(ii) {} void SetValue(int i, int j); void print() const; static void change(); }; int staticDemo::j = 100; void staticDemo::SetValue(int ii, int jj) { i = ii; j = jj; } void staticDemo::print() const { cout << "i: " << i << endl << "j: " << j << endl; } void staticDemo::change() { j++; } int main() { staticDemo so(10); so.print(); cout << endl << endl; so.SetValue(1000, 10000); cout << "after SetValue: " << endl; so.print(); staticDemo::change(); cout << "after change: " << endl; so.print(); // 不推荐这么做的。 so.change(); cout << "after so.change: " << endl; so.print(); return 0; }
运行结果:
i: 10 j: 100 after SetValue: i: 1000 j: 10000 after change: i: 1000 j: 10001 after so.change: i: 1000 j: 10002 Press any key to continue
浙公网安备 33010602011771号