C++:从指向类的指针访问成员结构的语法
我正在尝试访问成员结构变量,但我似乎无法获得正确的语法。 两个编译错误pr。 访问权限是: 错误 C2274:“函数式转换”:“.”的右侧非法 操作员 错误 C2228:“.otherdata”的左侧必须具有类/结构/联合 我尝试过各种改变,但没有成功。
#include <iostream>
using std::cout;
class Foo{
public:
struct Bar{
int otherdata;
};
int somedata;
};
int main(){
Foo foo;
foo.Bar.otherdata = 5;
cout << foo.Bar.otherdata;
return 0;
}
I'm trying to access a member structs variables, but I can't seem to get the syntax right.
The two compile errors pr. access are:
error C2274: 'function-style cast' : illegal as right side of '.' operator
error C2228: left of '.otherdata' must have class/struct/union
I have tried various changes, but none successful.
#include <iostream>
using std::cout;
class Foo{
public:
struct Bar{
int otherdata;
};
int somedata;
};
int main(){
Foo foo;
foo.Bar.otherdata = 5;
cout << foo.Bar.otherdata;
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
Bar
是Foo
内部定义的内部结构体。 创建Foo
对象不会隐式创建Bar
的成员。 您需要使用Foo::Bar
语法显式创建 Bar 对象。否则,
创建 Bar 实例作为 Foo 类中的成员。
Bar
is inner structure defined insideFoo
. Creation ofFoo
object does not implicitly create theBar
's members. You need to explicitly create the object of Bar usingFoo::Bar
syntax.Otherwise,
Create the Bar instance as member in
Foo
class.您只在那里定义一个结构,而不是分配一个。 试试这个:
如果你想在其他类中重用该结构体,你也可以在外部定义该结构体:
You only define a struct there, not allocate one. Try this:
If you want to reuse the struct in other classes, you can also define the struct outside:
您创建了一个嵌套结构,但从未在类中创建它的任何实例。 你需要这样说:
然后你可以说:
You create a nested structure, but you never create any instances of it within the class. You need to say something like:
You can then say:
您只声明 Foo::Bar 但没有实例化它(不确定这是否是正确的术语)
请参阅此处了解用法:
You are only declaring Foo::Bar but you don't instantiate it (not sure if that's the correct terminology)
See here for usage:
这里您刚刚定义了一个结构体,但没有创建它的任何对象。 因此,当您说
foo.Bar.otherdata = 5;
时,这是编译器错误。 创建一个 struct Bar 的对象,如Bar m_bar;
,然后使用Foo.m_bar.otherdata = 5;
Here you have just defined a structure but not created any object of it. Hence when you say
foo.Bar.otherdata = 5;
it is compiler error. Create a object of struct Bar likeBar m_bar;
and then useFoo.m_bar.otherdata = 5;