简体   繁体   中英

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

Function foo takes a vector of strings. It's defined as

bool foo(vector<string>& input);

When I call foo with:

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

my compiler gives the following error:

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

and points to { as the start of the error. This compiles fine in Xcode but I get the error when running the following via command line with:

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

What is wrong with my g++ syntax?

G++ Version Information:

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

Your command line specifies that the output file ("-o") should be called "-std=c++17" – it does not say anything about the language version, so you're compiling as C++03.
Remove the "-o" or add an actual file name.

Also, note that your "g++" is an alias for clang.

I took your code and tried to compile it. For me there was rather problem with trying to pass non const value to function. I changed function argument to const and it compiled and printed without any problem.

#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;
}

Compiled on: https://www.onlinegdb.com/online_c++_compiler

Function foo expects for an l-value.

You are generating an instance and passing it to the function. But lifetime of the object is not enough for the pass-by-reference call.

Here is an example below; instance of class A is immediately destructed.

#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;
}

Outputs:

main
A
~A
main

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM