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

use*_*073 1 c++

在下面的例子中我做了

MyClass a ();
Run Code Online (Sandbox Code Playgroud)

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

MyClass b = a();
a.a = 1;
Run Code Online (Sandbox Code Playgroud)

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

#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;
}
Run Code Online (Sandbox Code Playgroud)

And*_*owl 8

我被告知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();
}
Run Code Online (Sandbox Code Playgroud)

  • @RandyGaul:不,那将是`MyClass a;`或者,在C++ 11中,`MyClass a {}`. (3认同)