mardi 16 mai 2023

Error when using C++11 List Initialization Syntax g++ compiler

When I use list initialization to init my class members, the complier complains it's a function.

The g++ output:

$ g++ main.cpp -o main 
In file included from main.cpp:1:
./Cat.h:9:9: error: function definition does not declare parameters
    int age{};
        ^
...

compiler version:

$ g++ -v            
Apple clang version 14.0.3 (clang-1403.0.22.14.1)
Target: arm64-apple-darwin22.4.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin

source doe, Cat.h:

...
class Cat {
private:
    int age{};
    std::string name{};
public:
    Cat(int age, std::string name) : age(age), name(std::move(name)) {
        std::cout << "Cat: Constructor with two parameter is called" << std::endl;
    }
...
};

main.cpp

#include "Cat.h"

Cat getCat() {
    Cat cat{1, "Kitty"};
    return cat;
}

int main() {
    Cat cat = getCat();
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire