看似有效的 C++ 代码无法在 Mac 中使用 g++ 进行编译

时间:2021-03-06 17:58:32

标签: c++ macos struct g++ heap-memory

我目前正在学习 Udemy 的 C++ 课程。那里提供的代码工作正常,但对我来说无法编译:

#include <iostream>

struct Film {
    const int jahr;
    const char *titel;
    const char *regisseur;
};

int main() {

    Film star_wars_7{2015, "Star Wars the Force Awakens", "J. J. Abrams"};
    std::cout << star_wars_7.jahr << std::endl;
    std::cout << star_wars_7.titel << std::endl;
    std::cout << star_wars_7.regisseur << std::endl;

    Film star_wars_8{2017, "Star Wars the Last Jedi", "Rian Johnson"};
    std::cout << star_wars_8.jahr << std::endl;
    std::cout << star_wars_8.titel << std::endl;
    std::cout << star_wars_8.regisseur << std::endl;

    Film star_wars_9{2019, "Star Wars the Rise of Skywalker", "J. J. Abrams"};
    std::cout << star_wars_9.jahr << std::endl;
    std::cout << star_wars_9.titel << std::endl;
    std::cout << star_wars_9.regisseur << std::endl;

    return 0;
}

enter image description here

有谁知道,为什么我不能编译它?

另一件对我不起作用的事情是在堆上初始化一个变量。在课程中,是这样做的:

int *p_zahl = new int {4};

相反,我必须使用:

int *p_zahl = new int (4);

这是编译器的问题吗?

1 个答案:

答案 0 :(得分:0)

谢谢你们的帮助。问题是,我必须设置标志 -std=c++17。为了将此作为默认行为,我在 .bashrc 中添加了一个别名:

alias g++='g++ -std=c++17'
相关问题