c++ - 无法在C++中的main中定义结构

标签 c++ struct structure

不能在 C++ 的 main 中定义结构。

#include <iostream>
using namespace std;
int main()
{
    struct d
    {
        char name[20];
        int age;

    };
    struct d s,f;
    s = { "agent smith" , 17 };

    cout << s.name << " is 17 year old\n";
    return 0;
}

每当我编译我的代码时,我都会收到以下错误:-

$ g++ test.cpp 
test.cpp: In function ‘int main()’:
test.cpp:25:27: error: no match for ‘operator=’ (operand types are ‘main()::d’ and ‘<brace-enclosed initializer list>’)
  s = { "agent smith" , 17 };
                           ^
test.cpp:18:9: note: candidate: constexpr main()::d& main()::d::operator=(const main()::d&)
  struct d
         ^
test.cpp:18:9: note:   no known conversion for argument 1 from ‘<brace-enclosed initializer list>’ to ‘const main()::d&’
test.cpp:18:9: note: candidate: constexpr main()::d& main()::d::operator=(main()::d&&)
test.cpp:18:9: note:   no known conversion for argument 1 from ‘<brace-enclosed initializer list>’ to ‘main()::d&&’

我的代码有什么问题?我按照书上说的去做(c++ primer Plus 6thED)

最佳答案

尝试显式构造函数:

s = d{ "agent smith" , 17 };

或明确定义initialization

d s{"agent smith", 17};

(假设 C++11,所以使用 GCC - 最好至少是 GCC 6- 编译 with g++ -std=c++11 -Wall -Wextra -g)

附言。不要费心学习比 C++11 更早的东西。注意 C++17 最近是 approved (2017 年 9 月),但现在还太年轻,无法实现成熟。

关于c++ - 无法在C++中的main中定义结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46252809/

相关文章:

c++ - Eigen 3.2.1 + MKL = C4244 编译器警告

c++ - 在 C++ 中对二进制对象进行编码/解码的标准方法

data-structures - 在 MySQL 上存储城市、州和国家/地区的最佳方式是什么?

php - Symfony2 文件夹结构、优先级和顺序

c++ - OpenGL 帧率不一致

具有不同方法返回类型的 C++ 模板类设计

无法从链表中删除第一个节点

c - 二进制 == 在 'int' 和 'struct member' 之间,当两个值都是 int 时

c++ - 有没有一种方法可以存储多种类型的结构成员指针

c++ - 如何确定将哪种类型传递给模板定义的函数?