您的位置:首页 > 编程语言 > C语言/C++

c++类中的静态成员函数和静态成员变量

2014-06-09 08:52 330 查看
#include <iostream.h>

#include <stdio.h>

class Point

{

public:

void output()

{

printf("output====\n");

}

static void init()

{

printf("static====\n");

}

};

class Point2

{

public:

void output()

{

}

static void init()

{

// x = 0;

// y = 0;

}

private:

int x;

int y;

};

class Point3

{

public:

void output()

{

x = 0;

y = 0;

init();

}

static void init()

{

printf("static init!!!!\n");

}

private:

int x;

int y;

};

class Point4

{

public:

void output()

{

}

static void init()

{

x = 0;

y = 0;

printf("static init!!!!\n");

}

private:

static int x;

static int y;

};

class Point5

{

public:

void output()

{

}

static void init()

{

x = 0;

y = 0;

printf("static x=%d,y=%d\n",x,y);

}

private:

static int x;

static int y;

};

int Point5::x = 0;

int Point5::y = 0;

void main(void)

{

/************tese1************/

Point pt;

// pt.init();

// pt.output();

/************test2************/

/*error 编译就会有错误,因为没有实例化一个类的具体对象时,

类没有被分配内存空

*/

// Point::output();

/*编译就不会有错误,因为在类的定义时,

它静态数据和成员函数就有了它的内存区,它不属于类的任何一个具体对象。

*/

// Point::init();

/********test3 for Point2*******/

/*

在一个静态成员函数里错误的引用了数据成员,

还是那个问题,静态成员(函数),不属于任何一个具体的对象,那么在类的具体对象声明之前就已经有了内存区,

而现在非静态数据成员还没有分配内存空间,那么这里调用就错误了,就好像没有声明一个变量却提前使用它一样。

也就是说在静态成员函数中不能引用非静态的成员变量。

*/

// Point2::init();

/*********test4 for Point3******/

/*

这样就不会有任何错误。这最终还是一个内存模型的问题,

任何变量在内存中有了自己的空间后,在其他地方才能被调用,否则就会出错。

*/

// Point3::init();

// Point3 pt3;

// pt3.output();

/*********test5 for Point4******/

/*

可以看到编译没有错误,连接错误,这又是为什么呢?

这是因为静态的成员变量要进行初始化.

*/

// Point4::init();

/*********test6 for Point5******/

Point5::init();

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: