gcc 使用C++11列表初始化语法g++编译器时出错

xv8emn3q  于 2023-05-18  发布在  其他
关注(0)|答案(1)|浏览(253)

当我使用列表初始化来初始化我的类成员时,编译器抱怨它是一个函数。
g++输出:

$ 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{};
        ^
...

编译器版本:

$ 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

源代码,类别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;
}
xwmevbvl

xwmevbvl1#

代码

#include <iostream>

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

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

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

使用--std=c++17编译

/work/so/scratch/src/p0.cpp:8:9: warning: private field 'age'
      is not used [-Wunused-private-field]
    int age{};
        ^
1 warning generated.

编译时不使用--std=c++17

/work/so/scratch/src/p0.cpp:8:9: error: function definition
      does not declare parameters
    int age{};
        ^
/work/so/scratch/src/p0.cpp:9:17: error: function definition
      does not declare parameters
    std::string name{};
...

相关问题