c++11 - 错误 E0146 : Too many initializer values C++

标签 c++11 visual-c++ c++17

我有一个学校项目,我必须将 Student.h 中的 AM 用作 char*。AM 中必须包含数字。我不明白为什么我所做的事情不起作用。 学生.cpp

#include <iostream>
#include <string>
#include "Student.h"
using namespace std;
int main()
{
    Student dlg;
    dlg.AM[10]={2,1,3,9,0,2,6,6};
    
}

学生.h

#pragma once
#include <string>

using namespace std;

class Student
{
public:
    char *AM[20];
    string Name;
    unsigned int Semester = 1;
};

最佳答案

如果你确实需要你的学号是一个 char 字符串,那么你需要在将它们分配给数组之前将你的 int 转换为 char* 。

int main()
{
    Student dlg;
    int j = 0;
    for (auto i : {2,1,3,9,0,2,6,6})
    {
        auto strInt { std::to_string(i) }; // create a C++ string containing a int
        // next copy the internal memory of the C++ string to a read-writable memory buffer
        // and assign a pointer to that buffer casted to a char* to the appropriate slot in the array
        dlg.AM[j++] = static_cast<char*> (std::memcpy (new char[16], strInt.c_str(), strInt.size()));
    }
    // test
    for (int i = 0; i < 8; i++)
    {
        cout << dlg.AM[i] << ' ';
    }
}

您确定学号应该是 char* 吗?

关于c++11 - 错误 E0146 : Too many initializer values C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72495853/

相关文章:

c++ - 我需要将 std::move 移植到我的内核吗?

c++ - 这在 Visual Studio 中被视为 .NET 还是 IL?

c++ - 我想在基于 MFC 对话框的对话框中显示一些内容,但它在我的主对话框中没有显示任何内容!

c++ - 重载内置(固有?)功能

c++ - 如何优化获取数组中的最大值?

c++ - 重载方法覆盖 : Is there any simplification?

c++ - C++ lambda 函数的默认调用约定是什么?

模板类的 C++11 std::vector 在构造函数中带有参数

c++ - GCC 无法解析带有默认参数和以下参数包的方法调用

c++ - 调用存储在映射中的模板化 std::function