指向静态的指针

时间:2014-03-25 23:04:18

标签: c++ arrays string pointers

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

为什么我会收到错误?

1 个答案:

答案 0 :(得分:3)

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" };