简体   繁体   English

为什么我不能向前声明静态函数?

[英]Why can I not forward-declare a static function?

I need to forward-declare a class in my header file, like this: 我需要在头文件中向前声明一个类,如下所示:

class MyStaticClass;

I understand why one cannot forward-declare data members of this class. 我了解为什么不能转发声明此类的数据成员。 I used to think that you could however forward-declare functions. 我以前认为您可以向前声明函数。 I would like to declare a static function of this class, like this: 我想声明一个此类的静态函数,如下所示:

class MyStaticClass;
static int MyStaticClass::AddTwoNumbers(const int a, const int b);

This gives me a compile error though: 但这给了我一个编译错误:

error C2027: use of undefined type 'MyStaticClass'

Why can this not be done? 为什么不能做到这一点? Or is there a secret way of doing this after all? 还是有这样做的秘密方法?

This is not allowed because it would allow others to add member functions to a class without even editing the class itself. 不允许这样做,因为这将允许其他人甚至不编辑类本身就将成员函数添加到类中。

Consider this, 考虑一下

struct X
{
    static void f(float a) { std::cout << a << std::endl; }
 private:
    static int _data; //inaccessible to non-member
};

X::f(0); //convert 0 (an int) to float, and call X::f().

Now imagine someone came and forward-declare the following function, just before including header which defines the above class: 现在想象一下有人在包含定义上述类的标头之前,向前声明了以下函数:

static void X::f(int);

Now the previous call X::f(0) would give linker error ( unresolved name ) because now 0 wouldn't convert to float , because it does not need to as there is a declared function which accepts an int , though it is not defined — worse, if it is defined, then you wont even get the linker error and you would probably not easily know that a different function is being called. 现在,先前的调用X::f(0)会给出链接器错误( 未解析的名称 ),因为现在0不会转换为float ,因为它不需float ,因为有一个声明的函数接受一个int ,尽管不是定义的-更糟的是,如果已定义,则您甚至都不会收到链接器错误,并且您可能不容易知道正在调用其他函数。

Morever. Morever。 f(int) can now access the private member _data as well — in this way, anyone can access any private/protected members just by adding functions at whim. f(int)现在也可以访问private成员_data ,通过这种方式,任何人都可以通过添加临时功能来访问任何私有/受保护成员。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM