gpt4 book ai didi

c++ - 如何在类中声明结构?

转载 作者:可可西里 更新时间:2023-11-01 16:52:29 25 4
gpt4 key购买 nike

我想在一个私有(private)的类中声明一个结构,我想给同一个结构中的变量一个字符值,但我不能初始化它或 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 个元素)。

关于c++ - 如何在类中声明结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1609372/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com