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;
}
There are two ways to access the member of the structure using Structure pointer: Using ( * ) asterisk or indirection operator and dot ( . ) operator. Using arrow ( -> ) operator or membership operator.
You can access a structure member using pointers, of type structure, in the following ways; 1) Using the arrow operator: If the members of the structure are public then you can directly access them using the arrow operator ( -> ).
To access a member function by pointer, we have to declare a pointer to the object and initialize it (by creating the memory at runtime, yes! We can use new keyboard for this). The second step, use arrow operator -> to access the member function using the pointer to the object.
Declaring a structure pointer is similar to the declaration of a structure variable. To declare a structure pointer struct keyword is used followed by the structure name and pointer name with an asterisk * symbol. Members of a structure can be accessed from pointers using two ways that are.
You only define a struct there, not allocate one. Try this:
class Foo{
public:
struct Bar{
int otherdata;
} mybar;
int somedata;
};
int main(){
Foo foo;
foo.mybar.otherdata = 5;
cout << foo.mybar.otherdata;
return 0;
}
If you want to reuse the struct in other classes, you can also define the struct outside:
struct Bar {
int otherdata;
};
class Foo {
public:
Bar mybar;
int somedata;
}
Bar
is inner structure defined inside Foo
. Creation of Foo
object does not implicitly create the Bar
's members. You need to explicitly create the object of Bar using Foo::Bar
syntax.
Foo foo;
Foo::Bar fooBar;
fooBar.otherdata = 5;
cout << fooBar.otherdata;
Otherwise,
Create the Bar instance as member in Foo
class.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With