C ++错误 - “作为复合表达式处理的成员初始化表达式列表” [英] C++ error - "member initializer expression list treated as compound expression"

查看:613
本文介绍了C ++错误 - “作为复合表达式处理的成员初始化表达式列表”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到一个我不熟悉的C ++编译器错误。

I'm getting a C++ compiler error which I'm not familiar with. Probably a really stupid mistake, but I can't quite put my finger on it.

错误:

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 #include <iostream>
  2
  3 class Foo {
  4 public:
  5         Foo(float f) :
  6                 m_f(f)
  7         {}
  8
  9         float m_f;
 10 };
 11
 12 class Bar {
 13 public:
 14         Bar(const Foo& foo, int i) :
 15                 m_foo(foo),
 16                 m_i(i)
 17         {}
 18
 19         const Foo& m_foo;
 20         int m_i;
 21 };
 22
 23
 24 class Baz {
 25 public:
 26         Baz(const Foo& foo, int a) :
 27                 m_bar(foo, a)
 28         {}
 29
 30         const Bar& m_bar;
 31 };
 32
 33 int main(int argc, char *argv[]) {
 34         Foo a(3.14);
 35         Baz b(a, 5.0);
 36
 37         std::cout << b.m_bar.m_i << " " << b.m_bar.m_foo.m_f << std::endl;
 38
 39         return 0;
 40 }

注意:
看起来编译器正在评估逗号在第27行像这样:
http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=/com.ibm.xlcpp8l.doc/language/ref/co.htm

编辑:
好​​吧,我明白了Alan解释的问题。现在,对于额外的虚拟点,有人可以解释编译器(g ++)如何得出它给出的错误信息。

edit: Okay, I understand the problem as Alan explained it. Now, for extra imaginary points, can someone explain how the compiler (g++) came up with the error message it gave?

推荐答案

m_bar是一个引用,所以你不能构造一个。

m_bar is a reference, so you can't construct one.

正如其他人所说,你可以用引用的对象初始化引用,但是你不能像你想做的那样构造引用。

As others have noted, you can initialise references with the object it refers to, but you can't construct one like you're trying to do.

将第30行更改为

const Bar m_bar

,它会正确编译/运行。

and it'll compile / run properly.

这篇关于C ++错误 - “作为复合表达式处理的成员初始化表达式列表”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆