错误C2797:成员初始化列表中的列表初始化 [英] error C2797 : list initialization inside member initializer list
问题描述
我在看 MVA的C ++教程和下面提到的代码是由Kate不是我写的。但是她似乎没有编译显示任何错误,但在我的情况下,我得到以下错误:
错误1错误C2797: 'NamedRectangle :: _ name':列表初始化
在成员初始化程序列表或非静态数据成员初始化程序
未实现c:\users\abhimanyuaryan\documents \visual studio
2013 \projects\kate demos\17
inheritance\inheritance\\\
amedrectangle.h 12 1继承
代码中的第12行来自我的 NameRectangle
类,继承自 Rectangle
class:
class NamedRectangle:public Rectangle
{
public:
NamedRectangle(){}
NamedRectangle (std :: string initial_name,int initial_width,int initial_height)
:Rectangle {initial_width,initial_height},_name {initial_name} // - >这行
{}
std :: string get_name()const {return _name; }
private:
std :: string _name;
};
当我删除 std :: string
从构造函数以及 _name {initial_name}
代码编译。请解释我,不要把我当一个更高标准的有经验的程序员。我昨天才开始C ++。
James和我写了我们用于MVA日期和今天的代码时,编译器发生了变化。正在发生的是
_name {initial_name}
被解释为创建一个初始化列表,其中有一个项目,并使用它来初始化成员变量。
修正是切换到圆括号:
code> _name(initial_name)
这是造成一些人的困惑,至少有一个客户端为此打破了工作代码。
I was watching MVA's tutorial on C++ and the code I'm mentioning below is written by Kate not me. However she seems to get around with it without compiling showing any error but in my case I get the following error:
Error 1 error C2797: 'NamedRectangle::_name': list initialization inside member initializer list or non-static data member initializer is not implemented c:\users\abhimanyuaryan\documents\visual studio 2013\projects\kate demos\17 inheritance\inheritance\namedrectangle.h 12 1 Inheritance
Line 12 in the code is from my NameRectangle
class which inherits from Rectangle
class:
class NamedRectangle : public Rectangle
{
public:
NamedRectangle() { }
NamedRectangle(std::string initial_name, int initial_width, int initial_height)
: Rectangle{ initial_width, initial_height }, _name{ initial_name } //--> This line
{}
std::string get_name() const { return _name; }
private:
std::string _name;
};
when I remove std::string
initial_name from constructor as well as _name{initial_name}
the code compiles. Please explain me with not taking me as a higher standard experienced programmer. I started C++ yesterday only.
There was a compiler change between the time James and I wrote the code we used for the MVA day and today. What's happening is that
_name{ initial_name }
is being interpreted as creating an initializer-list with one item in it and using that to initialize the member variable. Which you can't do.
The fix is to switch to round brackets:
_name(initial_name)
This is causing confusion for a number of people and I have at least one client for whom this broke working code.
这篇关于错误C2797:成员初始化列表中的列表初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!