4

为什么这个复合语句作为由大括号(在 GNU C++ 中)和括号内括起来的语句序列似乎不是一个有效的语句表达式。

// my second program in C++
#include <iostream>
using namespace std;

int main ()
{
  cout << "Hello World! ";
  ({cout << "I'm a C++ program";}); 

}

编译器输出:

 In function 'int main()':
8:32: error: use of deleted function 'std::basic_ostream<char>::basic_ostream(const std::basic_ostream<char>&)'
In file included from /usr/include/c++/4.9/iostream:39:0,
                 from 2:
/usr/include/c++/4.9/ostream:58:11: note: 'std::basic_ostream<char>::basic_ostream(const std::basic_ostream<char>&)' is implicitly deleted because the default definition would be ill-formed:
     class basic_ostream : virtual public basic_ios<_CharT, _Traits>
           ^
/usr/include/c++/4.9/ostream:58:11: error: use of deleted function 'std::basic_ios<char>::basic_ios(const std::basic_ios<char>&)'
In file included from /usr/include/c++/4.9/ios:44:0,
                 from /usr/include/c++/4.9/ostream:38,
                 from /usr/include/c++/4.9/iostream:39,
                 from 2:
/usr/include/c++/4.9/bits/basic_ios.h:66:11: note: 'std::basic_ios<char>::basic_ios(const std::basic_ios<char>&)' is implicitly deleted because the default definition would be ill-formed:
     class basic_ios : public ios_base
           ^
In file included from /usr/include/c++/4.9/ios:42:0,
                 from /usr/include/c++/4.9/ostream:38,
                 from /usr/include/c++/4.9/iostream:39,
                 from 2:
/usr/include/c++/4.9/bits/ios_base.h:786:5: error: 'std::ios_base::ios_base(const std::ios_base&)' is private
     ios_base(const ios_base&);
     ^
In file included from /usr/include/c++/4.9/ios:44:0,
                 from /usr/include/c++/4.9/ostream:38,
                 from /usr/include/c++/4.9/iostream:39,
                 from 2:
/usr/include/c++/4.9/bits/basic_ios.h:66:11: error: within this context
     class basic_ios : public ios_base
           ^

我在What's this C++ 语法中找到了关于“语句表达式”的一个很好的答案,它在预期表达式的位置放置了一个大括号包围的块?

4

1 回答 1

7

From the reference:

The last thing in the compound statement should be an expression followed by a semicolon; the value of this subexpression serves as the value of the entire construct.

and

In G++, the result value of a statement expression undergoes array and function pointer decay, and is returned by value to the enclosing expression.

This means in the expression:

({cout << "I'm a C++ program";}); 

the object std::cout is returned by value. This invokes the copy constructor of std::basic_ostream, which is deleted, and hence the error.

于 2020-05-29T18:50:48.187 回答