我有一个学校项目,我必须将 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/