具有静态链接的成员函数 [英] Member function with static linkage

查看:176
本文介绍了具有静态链接的成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图理解以下错误的原因:

I'm trying to understand why the following is an error:

class Foobar {
 public:
  static void do_something();
};

static void Foobar::do_something() {} // Error!

int main() {
  Foobar::do_something();
}

此错误与错误:无法声明成员函数'static void Foobar ::在g ++中, do_something()'具有静态链接;在clang ++中,错误:'静态'只能在类定义中指定。

This errors with "error: cannot declare member function 'static void Foobar::do_something()' to have static linkage" in g++, and "error: 'static' can only be specified inside the class definition" in clang++.

我知道解决此问题的方法是在第6行的do_something定义中删除 static,但是我不明白为什么这是一个问题。是世俗的原因,例如 C ++语法要求如此,还是发生了更复杂的事情?

I understand that the way to fix this is to remove "static" in the definition of do_something on line 6. I don't, however, understand why this is an issue. Is it a mundane reason, such as "the C++ grammar dictates so", or is something more complicated going on?

推荐答案

The关键字 static 在C ++中具有几种不同的含义,您上面编写的代码以两种不同的方式使用它们。

The keyword static has several different meanings in C++, and the code you've written above uses them in two different ways.

在在成员函数的上下文中, static 表示此成员函数没有接收者对象。基本上,这是一个嵌套在类范围内的普通函数。

In the context of member functions, static means "this member function does not have a receiver object. It's basically a normal function that's nested inside of the scope of the class."

在函数声明的上下文中, static 意味着此函数的作用域仅限于此文件,不能从其他地方调用。

In the context of function declarations, static means "this function is scoped only to this file and can't be called from other places."

通过编写实现该功能的情况

When you implemented the function by writing

static void Foobar::do_something() {} // Error!

编译器在这里将 static 解释为 I在实现该成员函数的过程中,我想使该函数仅在此文件本地。这在C ++中是不允许的,因为它会引起一些混乱:如果多个不同的文件都定义了自己的成员函数实现,然后将其声明为 static 以避免链接时发生冲突,请调用

the compiler interpreted the static here to mean "I'm implementing this member function, and I want to make that function local just to this file." That's not allowed in C++ because it causes some confusion: if multiple different files all defined their own implementation of a member function and then declared them static to avoid collisions at linking, calling the same member function from different places would result in different behavior!

幸运的是,正如您所指出的,有一个简单的解决方法:只需删除 static 定义中的关键字:

Fortunately, as you noted, there's an easy fix: just delete the static keyword from the definition:

void Foobar::do_something() {} // Should be good to go!

这很好,因为编译器已经知道 do_something 是一个静态成员函数,因为您之前已经介绍过它。

This is perfectly fine because the compiler already knows that do_something is a static member function, since you told it about that earlier on.

这篇关于具有静态链接的成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆