8 c++
我想在一个私有的类中声明一个结构,我想给同一个结构中的变量赋一个字符值,但我不能初始化它或者它:
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();
}
Run Code Online (Sandbox Code Playgroud)
Dou*_* T. 20
您已经描述了一个名为"p"的类型,它是一个结构.还没有类型p的东西.因此你的
p->...
Run Code Online (Sandbox Code Playgroud)
电话没有意义.
试着宣布
p pInstance;
Run Code Online (Sandbox Code Playgroud)
在你的班级并使用它,即:
void setme()
{
this->pInstance.grade=99;
this->pInstance.name[25]='g'; //here is the problem
}
Run Code Online (Sandbox Code Playgroud)
请注意,即使这样,您对名称[25]的赋值也将失败,因为该数组的允许索引为0到24(总共25个元素).
jke*_*ian 14
你这里有两个严重的问题
struct p
{
char name[25];
int grade;
};
Run Code Online (Sandbox Code Playgroud)
这定义了一个名为p 的结构类型.我想你想做的是
struct
{
char name[25];
int grade;
} p;
Run Code Online (Sandbox Code Playgroud)
这将声明一个名为p 的结构,其中包含名称和成员成员变量.
你的第二个严重问题是你分配:
this->p::name[25]='g'; //here is the problem
Run Code Online (Sandbox Code Playgroud)
这将'g'分配给数组名称的第26个元素.(数组为0索引)
不是吗
struct { ... } p; // variable of struct-type definition.
Run Code Online (Sandbox Code Playgroud)
不
struct p { ... }; // type 'struct p' definition.
Run Code Online (Sandbox Code Playgroud)
?
使用 typedef 将结构定义放在类之外。通过在 .cpp 文件中定义该结构,它将在类之外不可见。
#include <iostream>
typedef struct _foo
{
int a;
} foo;
class bar
{
public:
void setA(int newa);
int getA();
private:
foo myfoo;
};
void bar::setA(int newa)
{
myfoo.a = newa;
}
int bar::getA()
{
return myfoo.a;
}
using namespace std;
int main()
{
bar mybar;
mybar.setA(17);
cout << mybar.getA() << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)