C++ ctor 不允许返回类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2579657/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 23:58:41  来源:igfitidea点击:

Ctor not allowed return type

c++constructor

提问by There is nothing we can do

Having code:

有代码:

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

B::B(const B& pattern)
{

}

I'm getting err msg:
'Error 1 error C2533: 'B::{ctor}' : constructors not allowed a return type'

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

Any idea why?
P.S. I'm using VS 2010RC

知道为什么吗?
PS 我使用的是 VS 2010RC

回答by GManNickG

You're missing a semicolon after your structdefinition.

您在struct定义后缺少分号。



The error is correct, constructors have no return type. Because you're missing a semicolon, that entire struct definition is seen as a return type for a function, as in:

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

// vvv return type vvv
struct { /* stuff */ } foo(void)
{
}

Add your semicolon:

添加分号:

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)
{

}

回答by There is nothing we can do

You need a better compiler. With g++:

你需要一个更好的编译器。使用 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

The semicolon is needed because it terminates a possible list of instances of the struct:

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

struct B {
...
} x, y, z;

Creates three instances of B called x, y and z. This is part of C++'s C heritage, and will still be there in C++0x.

创建 B 的三个实例,称为 x、y 和 z。这是 C++ 的 C 遗产的一部分,在 C++0x 中仍然存在。