c++类中static的使用

原文链接:https://www.csdn.net/gather_20/NtzaMgxsODQtYmxvZwO0O0OO0O0O.html

C++ Programming language 10.2.4中提到一句话:静态成员,包括函数和数据成员,都必须在某个地方另行定义,“另行”究竟指的是什么意思呢?

如果把包含有static成员的类的定义放在头文件中,而在源文件中调用这个static成员变量将无法通过编译,正确的做法是在相应的源文件中重新定义这个类成员变量

第一种情况:

 #include <iostream>
 using namespace std;
  class C
  {
 	public:
 		static int x;
 		static int f ()
 		{
 			return x;
 		}
 	};
 int main ()
{
	cout << C::f() << endl;
	return 0;
}

报出了main.cc:11: undefined reference to `C::x’的链接期错误,原因是x作为static成员变量没有在类外定义。

第二种情况

 #include <iostream>
 using namespace std;
  class C
  {
 	public:
 		static int x;
 		static int f ()
 		{
 			return x;
 		}
 	};
 static int C::x=4;
 int main ()
{
	cout << C::f() << endl;
	return 0;
}

报出了main.cc:15: error: ‘static’ may not be used when defining (as opposed to declaring) a static data member的编译期错误,这又是为什么呢?

第三种情况(编译通过)

 #include <iostream>
 using namespace std;
  class C
  {
 	public:
 		static int x;
 		static int f ()
 		{
 			return x;
 		}
 	};
 int C::x=4;
 int main ()
{
	cout << C::f() << endl;
	return 0;
}

这次编译链接通过,程序运转正常,原来2中的问题是在类外定义static变量时要省去static关键字

第四种情况

 #include <iostream>
 using namespace std;
  class C
  {
 	public:
 		static int x;
 		static int f ()
 		{
 			return x;
 		}
 	};
 int main ()
{
	int C::x=4;
	cout << C::f() << endl;
	return 0;
}

这一次又报出了main.cc:17: error: invalid use of qualified-name ‘C::x’的错误,原来static变量在编译单元内的定义必须是全局的

总结:
必须在某个地方另行定义,但static成员函数可以在类内定义
static成员变量必须在类外定义,且必须在编译单位内全员定义,不能定义在某个域内,如函数等
static成员(包括变量和函数),在类外重新定义时,必须省略原有的static关键字。

  • 13
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值