G++ 命令抛出 "expected '(' for function-style cast or type construction"

G++ command throws "expected '(' for function-style cast or type construction"

函数 foo 接受一个字符串向量。它被定义为

bool foo(vector<string>& input);

当我调用 foo 时:

foo(vector<string>{"abc"});

我的编译器给出了以下错误:

error: expected '(' for function-style cast or type construction

并指向 { 作为错误的开始。这在 Xcode 中编译得很好但是当 运行 通过命令行使用以下命令时我得到错误:

g++ -o -std=c++17 main.cpp

我的 g++ 语法有什么问题?

G++版本信息:

g++ --version                   
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/4.2.1
Apple clang version 11.0.3 (clang-1103.0.32.59)
Target: x86_64-apple-darwin19.4.0
Thread model: posix

函数 foo 需要一个左值。

您正在生成一个实例并将其传递给函数。但是对象的生命周期对于传递引用调用来说是不够的。

下面是一个例子; class A 的实例立即被销毁。

#include <iostream>
#include <vector>
#include <string>

using namespace std;

class A {
  public:
  A(int m): m(m) {
    cerr << __func__ << endl;
  }
  ~A() {
    cerr << __func__ << endl;
  }
  int m;
};

int main() {
  cerr << __func__ << endl;
  A(5);
  cerr << __func__ << endl;
  return 0;
}

输出:

main
A
~A
main

你的命令行指定输出文件(“-o”)应该被称为“-std=c++17”——它没有说明语言版本,所以你编译为 C+ +03.
删除“-o”或添加实际文件名。

另请注意,您的“g++”是 clang 的别名。

我拿了你的代码并尝试编译它。对我来说,尝试将非 const 值传递给函数存在相当大的问题。我将函数参数更改为 const 并且编译和打印没有任何问题。

#include <iostream>
#include <vector>

bool foo(const std::vector<std::string>& v) {
    for (auto& a : v) { std::cout << a << std::endl; } 
    return true;
}

int main()
{
    bool result = foo(std::vector<std::string> {"1", "2", "3" });
    // do something with result
    return 0;
}

编译于:https://www.onlinegdb.com/online_c++_compiler