将变量声明为函数是什么意思?

What does it mean to declare a variable as a function?

本文关键字:是什么 意思 函数 变量 声明      更新时间:2023-10-16

在下面的例子中,我做了

MyClass a ();

我被告知a实际上是一个返回MyClass的函数,但下面两行都不起作用。

MyClass b = a();
a.a = 1;

那么a是什么,我可以用它做什么?

#include "stdafx.h"
#include "iostream"
using namespace std;
class MyClass {
    public:
        int a;
};
int _tmain(int argc, _TCHAR* argv[])
{
    MyClass a ();
    // a is a function? what does that mean? what can i do with a?
    int exit; cin >> exit;
    return 0;
}

我被告知a实际上是一个返回MyClass[…]的函数

这是一个函数声明。它只是声明了一个名为a的函数,并让编译器知道它的存在及其签名(在本例中,该函数不接受任何参数,并返回一个类型为MyClass的对象)。这意味着您可以稍后提供该函数的定义:
#include "iostream"
using namespace std;
class MyClass {
    public:
        int a;
};
int _tmain()
{
    MyClass a (); // This *declares* a function called "a" that takes no
                  // arguments and returns an object of type MyClass...
    MyClass b = a(); // This is all right, as long as a definition for
                     // function a() is provided. Otherwise, the linker
                     // will issue an undefined reference error.
    int exit; cin >> exit;
    return 0;
}
MyClass a() // ...and here is the definition of that function
{
    return MyClass();
}