[英]C++ error - “member initializer expression list treated as compound expression”
我收到了一個我不熟悉的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 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 /語言/ REF / co.htm
編輯:好的,我理解艾倫解釋的問題。 現在,對於額外的虛構點,有人可以解釋編譯器(g ++)如何提供它給出的錯誤消息嗎?
m_bar是一個引用,因此您無法構造一個。
正如其他人所指出的那樣,你可以用引用的對象初始化引用,但是你不能像你想要的那樣構造引用。
將第30行更改為
const Bar m_bar
並且它將正確編譯/運行。
m_bar被聲明為“const引用”,因此無法使用您提供的構造函數進行實例化。
考慮使m_bar成為成員,或者將預先構造的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提供了更多的gnomic錯誤:
error C2059: syntax error : 'constant'
簡單地說,你不能初始化這樣的引用。
雖然這個問題很老,但對於未來的讀者,我會指出標記為答案的項目是不正確的。 確實可以構建參考。
在初始化程序行中,代碼m_bar(foo, a)
嘗試使用(foo,a)
作為m_bar的構造函數。 該錯誤告訴您將忽略foo
並且您無法構造一個來自int a
bar。 以下正確的語法將編譯無錯誤:
m_bar (*new Bar(foo,a))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.