如何在类中声明结构?

2024-06-14

我想在一个类中声明一个私有的结构,并且我想为同一结构中的变量提供一个字符值,但我无法初始化它或 cin 它:

class puple
{
private:
    struct p
    {
        char name[25];
        int grade;
    };
public:
    puple(){};
    void setme()
    {
        this->p::grade=99;
        this->p::name[25]='g';  //here is the problem
    }
    void printme()
    {
        cout<<"Name:  "<<this->p::name<<endl;
        cout<<"Grade:  "<<this->p::grade<<endl;
    }
};
void main()
{
    puple pu1;
    pu1.setme();
    pu1.printme();
}

您描述了一种名为“p”的类型,它是一个结构体。周围还没有 p 类型的东西。因此你的

p->...

打电话没有任何意义。

尝试声明

p pInstance;

在你的课堂上并使用它,即:

void setme()
{
    this->pInstance.grade=99;
    this->pInstance.name[25]='g';  //here is the problem
}

请注意,即使这样,您对 name[25] 的分配也会失败,因为该数组允许的索引为 0 到 24(总共 25 个元素)。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在类中声明结构? 的相关文章

随机推荐