C++;错误-“;成员初始值设定项表达式列表被视为复合表达式; 我得到了一个我不熟悉的C++编译器错误。这可能是一个非常愚蠢的错误,但我不能完全指出这一点

C++;错误-“;成员初始值设定项表达式列表被视为复合表达式; 我得到了一个我不熟悉的C++编译器错误。这可能是一个非常愚蠢的错误,但我不能完全指出这一点,c++,C++,错误: test.cpp:27: error: member initializer expression list treated as compound expression test.cpp:27: warning: left-hand operand of comma has no effect test.cpp:27: error: invalid initialization of reference of type ‘const Bar&’ from expression

错误:

test.cpp:27: error: member initializer expression list treated as compound expression
test.cpp:27: warning: left-hand operand of comma has no effect
test.cpp:27: error: invalid initialization of reference of type ‘const Bar&’ from expression of type ‘int’
代码:

1#包括
2.
三等富{
4公众:
5个浮点数(浮点数f):
6M_f(f)
7         {}
8.
9个浮点数;
10 };
11
12级酒吧{
13公众:
14巴(恒富和恒富,国际一级):
15M_foo(foo),
16M_i(i)
17         {}
18
19康斯特富美富;
20国际货币单位;
21 };
22
23
24级Baz{
25公众:
26巴兹(恒富和富,国际a):
27米酒吧(富,a)
28         {}
29
30个钢筋和钢筋;
31 };
32
33内部主(内部argc,字符*argv[]){
34富a(3.14);
35巴(a,5.0),;
36
37 std::coutmu bar被声明为“const引用”,因此不能用您提供的构造函数实例化


考虑将m_bar设为成员,或将预构造的bar对象传递给构造函数。

m_bar是一个引用,因此无法构造

正如其他人所指出的,您可以使用引用的对象初始化引用,但不能像您正在尝试的那样构造引用

将第30行改为

const Bar m_bar

并且它将正确编译/运行。

您可以在以下代码中更清楚地看到问题:

struct B {
    B( int a, int x  ) {}
};

int main() {
    const B & b( 1, 2);
}
这会使用g++产生以下错误:

t.cpp: In function 'int main()':
t.cpp:6: error: initializer expression list treated as compound expression
t.cpp:6: error: invalid initialization of reference of type 'const B&' from expression of type int'
VC++6.0给出了更具灵知性的错误:

 error C2059: syntax error : 'constant'

简单地说,你不能像那样初始化引用。

虽然这个问题很老,但对于未来的读者,我将指出,标记为答案的项目是不正确的。确实可以构造引用

在初始值设定项行中,代码
MU bar(foo,a)
试图使用
(foo,a)
作为MU bar的构造函数。错误告诉您将忽略
foo
,并且不能用
int a
构造条形图。以下正确语法将编译为无错误:

m_bar (*new Bar(foo,a))

g++是如何产生错误消息的?不知道。Sun Studio给出了错误行27:错误:m_bar的初始值设定项太多。它提供了更多的信息。简短的回答是,许多编译器的错误消息往往有点难以读取。额外的一点是:它产生了这个错误,因为代码试图构造ct a
条形图
,构造函数为
(foo,a)
。错误消息告诉您foo将被忽略,并且它无法将
int a
转换为Bar。我知道这是一个古老的问题,但您标记为答案的内容是错误的和误导性的。我发布了代码,说明您如何将
m_Bar
的声明放在一边,并将其编译。a标记为correct的swer肯定是正确的!虽然可以构造引用,但并不意味着应该构造引用!(尽管您在编译器消息方面走的是对的,但我同意!)
m_bar (*new Bar(foo,a))