C++类中static成员函数的声明与实现

 

基本的语法,相关的资料可以参考:http://cplusplus.syntaxerrors.info/index.php?title=Cannot_declare_member_function_%E2%80%98static_int_Foo::bar()%E2%80%99_to_have_static_linkage

 

英文解释:

if you declare a method to be static in your .cc file.

The reason is that static means something different inside .cc files than in class declarations It is really stupid, but the keywordstatic hasthree different meanings. In the .cc file, the static keyword means that the function isn't visible to any code outside of that particular file.

This means that you shouldn't use static in a .cc file to define one-per-class methods and variables. Fortunately, you don't need it. In C++, you are not allowed to have static variables or static methods with the same name(s) as instance variables or instance methods. Therefore if you declare a variable or method as static in the class declaration, you don't need thestatic keyword in the definition. The compiler still knows that the variable/method is part of the class and not the instance.

 

错误的:

 Foo.h:
class Foo
{
   public:
     static int bar();
};
Foo.cc:
static int Foo::bar()
{
   // stuff
}
正确的:

 Foo.h:
class Foo
{
   public:
     static int bar();
};
Foo.cc:
int Foo::bar()
{
   // stuff
}
这个也是正确的:

 Foo.h:
class Foo
{
   public:
     static int bar()
       {
         // stuff
       };
};

第一种写法编译出现“cannot declare member function ******  to have static linkage”。

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C++中,类的静态成员函数是属于类本身而不是类对象的成员函数。静态成员函数声明时使用了static关键字。静态成员函数在使用时可以直接通过类名加作用域解析运算符::调用,而不需要通过类对象来调用。 静态成员函数声明实现可以分离,意味着可以将静态成员函数声明和定义放在不同的文件中。这种分离的用途主要有两个方面: 第一,可以将静态成员函数声明放在类的头文件中,将定义放在实现文件中,这样可以提高代码的可读性和可维护性,使得类的接口部分和实现部分分离开来。 第二,当多个源文件需要使用同一个类的静态成员函数时,可以将函数声明放在一个公共的头文件中,而将函数的定义放在不同的源文件中,然后将这些源文件编译链接在一起。这样可以避免在多个源文件中重复定义静态成员函数,减少了代码的冗余,提高了编译的效率。 需要注意的是,静态成员函数在定义时无法访问类的非静态成员变量和非静态成员函数,因为静态成员函数没有this指针。但是静态成员函数可以访问类的静态成员变量和静态成员函数。 总结起来,类的静态成员函数声明实现分离可以提高代码的可读性、可维护性和代码复用性。它允许将类的接口部分和实现部分分开,并使得多个源文件可以共享同一个类的静态成员函数而不需要重复定义。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值