首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

老大们 请问下 static 是声明还是定义

2012-03-07 
老大们 请教下 static 是声明还是定义?TO:Vitin(卫亭)相关主题的贴:http://community.csdn.net/Expert/top

老大们 请教下 static 是声明还是定义?
TO:   Vitin(卫亭)
相关主题的贴:http://community.csdn.net/Expert/topic/5662/5662204.xml?temp=.3433496

若是声明的话,下面代码就不该有地址输。因为没定义,不该有内存地址。

==================================   1.h   ========================


#include   <iostream>
using   namespace   std;


class   AA
{
public:
AA()
{
cout < <this < <endl;
}

};
static   AA   one;

==================================1.cpp===============================


#include   "1.h "

int   main()
{
}

====================================2.cpp==============================
#include   "1.h "


************************************************************************

若是定义的话:

#include   <iostream>
using   namespace   std;

class   alloc
{
};

template   <class   T,   class   ALLOC=alloc,   size_t   Buff_SIZE=0>
class   deque
{
public:
deque()
{
cout < < "deque " < <endl;
}
};

template <class   T,class   temp=deque <T> >
class   stack
{
public:
stack()
{
cout < < "stack ";
}
static   temp   a;//只有删除   static   后才有(cout < < "stack ";
)输出

};

int   main()
{
stack <int> ();
}

[解决办法]
static AA one;

申明一个全局的表态AA变量,在程序启动的时候(也就是在main函数之前),它就已被分配了空间


static temp a;//
类里的staitc 变量声明.初始化在放在类外部进行


[解决办法]
如果按你那样些应该是声明
定义全局静态的时候在类或结构外定义
楼上的说的差不多
[解决办法]
在第一个例子里,
static AA one;
是一个定义,请注意它在全局域(所有的函数定义和类定义之外)。
这里的static的语义是内部链接。

在第二个例子里,
static temp a;
是一个声明,请注意它在类定义中。这里的static的语义是静态成员。
为了使这个声明有效,你还需要在全局域中定义它,如
template <class T,class temp>
temp stack <T, temp> ::a;

只有在静态整型常量才可以在类定义中定义,如
class StaticTest
{
public:
static const int MY_INT_CONST = 1; //此处是定义
};


热点排行