Cannot declare member function ...to have static linkage"问题

在GCC下,这是一个warning,然后查找了下原因,是因为static外置导致的。

查看C++ primer
“静态成员函数的声明除了在类体中的函数声明前加上关键字static 以及不能声明为
const 或volatile 之外与非静态成员函数相同出现在类体外的函数定义不能指定关键字
static”

那究竟是为什么呢? 这有用什么目的和用途?

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 keyword static has three 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 the static keyword in the definition. The compiler still knows that the variable/method is part of the class and not the instance.

翻译一下:


1. static 在声明处和.cc文件中表示的东西是不同的。

2. static有三种不同的意义:a. 在.cc文件中,static关键字表示函数对外部文件时不可见的,也就是你不应该在.cc文件中使用static来定义一个类的方法或者变量;b. C++中,不允许定义带相同名字的static 实例变量或者函数,因此,如果你声明了一个变量或者函数为静态,那么就不需要再定义处添加static。

然后在CSDN上找一个比较不错的回答:


怎么说呢, 这是一个作用域的问题!
成员函数的作用域是类域, 而在类体外加上static不是表示静态函数,表示的是函数拥有文件域(file scope)
而类域是小于文件域,强行把类域扩大到文件域,就会出错。
如下代码:
class CA {
public:
static void display(void);
};

static void CA::display(void) { // ERROR!
cout << "Hello CA!" << endl;
}

int main(int argc, char* argv[]) {
CA::display();
}
 
---------------------  
作者:路人戊戌乙亥  
来源:CSDN  
原文:https://blog.csdn.net/passerbysrs/article/details/40784985  
版权声明:本文为博主原创文章,转载请附上博文链接!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值