C++:从类指针访问成员结构的语法
问题描述:
我试图访问一个成员结构变量,但我似乎无法得到正确的语法。 这两个编译错误公关。访问是: 错误C2274:'功能风格强制转换':非法作为'。'的右侧。运算符 错误C2228:'.otherdata'的左边必须有class/struct/union 我试过了各种更改,但都没有成功。C++:从类指针访问成员结构的语法
#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;
}
答
你只在那里定义一个结构体,而不是分配一个结构体。试试这个:
class Foo{
public:
struct Bar{
int otherdata;
} mybar;
int somedata;
};
int main(){
Foo foo;
foo.mybar.otherdata = 5;
cout << foo.mybar.otherdata;
return 0;
}
如果你想重用其他类的结构,也可以外定义的结构:
struct Bar {
int otherdata;
};
class Foo {
public:
Bar mybar;
int somedata;
}
答
Bar
里面Foo
定义的内部结构。创建Foo
对象不会隐式创建Bar
的成员。您需要使用Foo::Bar
语法明确创建Bar的对象。
Foo foo;
Foo::Bar fooBar;
fooBar.otherdata = 5;
cout << fooBar.otherdata;
否则,
在Foo
类来创建栏实例作为成员。
class Foo{
public:
struct Bar{
int otherdata;
};
int somedata;
Bar myBar; //Now, Foo has Bar's instance as member
};
Foo foo;
foo.myBar.otherdata = 5;
答
您创建了一个嵌套结构,但是您从不在类中创建它的任何实例。你需要这样说:
class Foo{
public:
struct Bar{
int otherdata;
};
Bar bar;
int somedata;
};
那么你可以说:
foo.bar.otherdata = 5;
答
你只宣布美孚::酒吧,但(如果这是正确的术语不知道)你不实例化它
看到这里的用法:
#include <iostream>
using namespace std;
class Foo
{
public:
struct Bar
{
int otherdata;
};
Bar bar;
int somedata;
};
int main(){
Foo::Bar bar;
bar.otherdata = 6;
cout << bar.otherdata << endl;
Foo foo;
//foo.Bar.otherdata = 5;
foo.bar.otherdata = 5;
//cout << foo.Bar.otherdata;
cout << foo.bar.otherdata << endl;
return 0;
}
答
struct Bar{
int otherdata;
};
在这里,您刚刚定义了一个结构,但未创建任何对象。因此,当你说foo.Bar.otherdata = 5;
这是编译器错误。创建一个对象的结构像吧像Bar m_bar;
然后用Foo.m_bar.otherdata = 5;
谢谢,完全忘了那个。并且像魅力一样工作。 – 2009-05-27 11:07:37
代码不完全相同。在第一个示例中,Bar结构的名称实际上是Foo :: Bar。 – 2009-05-27 11:09:09