指向静态的指针

Pointer to Static

本文关键字:指针 静态      更新时间:2023-10-16

Student有一个静态成员Year,该成员是指向std::string的指针,该指针应该指向一个动态分配的数组。

class Student
{
private:
    string name;
    int year;
    string semester;
    int AmtClass;
    static string *Year[4];
    //Skipping the public members
};
string *Student::Year[4] = { "Freshman", "Sophomore", "Junior", "senior" };

尝试初始化Year时出现问题:

ERROR: Cannot convert 'const char*' to 'std::string*' in initialization

为什么我得到错误?

struct A
{
    static std::string *cohort;
};
std::string * A::cohort = new std::string[4];

不清楚为什么要动态分配数组。你可以用std::array<std::string, 4>std::dynarray<std::string>

当你更新你的帖子时,你应该写

std::string * Student::Year = new std::string[4] { "Freshman", "Sophomore", "Junior", "senior" };

struct Student
{
    static std::string Year[];
};

std::string Student::Year[4] = { "Freshman", "Sophomore", "Junior", "senior" };