V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
XIVN1987
V2EX  ›  C++

error: invalid conversion from ‘const char*’ to ‘char’ [-fpermissive]

  •  
  •   XIVN1987 · Jun 14, 2020 · 2961 views
    This topic created in 2145 days ago, the information mentioned may be changed or developed.
    《 C++ Crash Course 》上有个例程如下:
    ``` c++
    struct JohanVanDerSmut
    {
    bool gold = true;
    int year_of_smelting_accident{1970};
    char key_location[8] = {"x-rated"};
    };
    ```

    我编译后程序报错:
    error: invalid conversion from ‘const char*’ to ‘char’ [-fpermissive]
    char key_location[8] = {"x-rated"};
    ^

    是编译器版本的问题吗??我用的是 gcc 5.4
    8 replies    2020-06-15 10:29:19 +08:00
    wssy
        1
    wssy  
       Jun 14, 2020 via Android
    这段代码应该是没有问题的,得参考下 cppreference 中的 copy-initialization 。
    我看下资料才行。

    你开启 c++11 了吗?
    Chihaya0824
        2
    Chihaya0824  
    PRO
       Jun 14, 2020
    char key_location[8] = {'x-rated'};试试?
    Chihaya0824
        3
    Chihaya0824  
    PRO
       Jun 14, 2020
    @Chihaya0824 RE #2 我傻了()肯定不对的
    wssy
        4
    wssy  
       Jun 14, 2020 via Android
    刚刚看了,这个是 aggregate-initialization 的一种特例,就算 11 以前也是支持的。
    你看看是不是前面某些地方出了些错误,导致后面连着错。。。
    msg7086
        5
    msg7086  
       Jun 15, 2020
    int main() { std::cout << __cplusplus << std::endl; }

    GCC 5.4 = 199711 = C++98

    可以看这里 https://gist.github.com/ax3l/53db9fa8a4f4c21ecc5c4100c0d93c94

    建议还是不要用 22 年前的标准来跑了。
    XIVN1987
        6
    XIVN1987  
    OP
       Jun 15, 2020
    @msg7086

    我加了 -std=c++14 选项的,,不加这个选项会报下面的警告

    warning: non-static data member initializers only available with -std=c++11 or -std=gnu++11
    msg7086
        7
    msg7086  
       Jun 15, 2020
    @XIVN1987 我用 G++尝试编译了,C++11/14/17/2x 都能过。

    你可以把比较完整的源码贴到 gist,连带你编译的命令一起贴出来看看。
    XIVN1987
        8
    XIVN1987  
    OP
       Jun 15, 2020
    @msg7086

    感谢,,用新版编译器编译确实没问题了
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3926 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 65ms · UTC 04:12 · PVG 12:12 · LAX 21:12 · JFK 00:12
    ♥ Do have faith in what you're doing.