Ctor不允许返回类型

The*_* do 41 c++ constructor

有代码:

struct B
{
    int* a;
    B(int value):a(new int(value))
    {   }
    B():a(nullptr){}
    B(const B&);
}

B::B(const B& pattern)
{

}
Run Code Online (Sandbox Code Playgroud)

我收到错误消息:
'错误1错误C2533:'B :: {ctor}':构造函数不允许返回类型'

知道为什么吗?
PS我正在使用VS 2010RC

GMa*_*ckG 70

struct定义之后,你错过了一个分号.


错误是正确的,构造函数没有返回类型.因为您缺少分号,所以整个结构定义被视为函数的返回类型,如:

// vvv return type vvv
struct { /* stuff */ } foo(void)
{
}
Run Code Online (Sandbox Code Playgroud)

添加分号:

struct B
{
    int* a;
    B(int value):a(new int(value))
    {   }
    B():a(nullptr){}
    B(const B&);
}; // end class definition

// ah, no return type
B::B(const B& pattern)
{

}
Run Code Online (Sandbox Code Playgroud)

  • @Martin:它不仅仅是来自C的"宿醉".例如:`class {/*...*/} object;`是允许的,所以分号是*需要*告诉编译器它到达了结束类定义. (10认同)

小智 12

你需要一个更好的编译器.使用g ++:

a.cpp:1: error: new types may not be defined in a return type
a.cpp:1: note: (perhaps a semicolon is missing after the definition of 'B')
a.cpp:5: error: return type specification for constructor invalid
Run Code Online (Sandbox Code Playgroud)

分号是必需的,因为它终止了结构的可能实例列表:

struct B {
...
} x, y, z;
Run Code Online (Sandbox Code Playgroud)

创建三个名为x,y和z的B实例.这是C++ C语言遗产的一部分,并且仍将存在于C++ 0x中.

  • @atch你现在是解析C++的专家吗?关键是结构之后有***构造函数. (2认同)