accessing struct variable inside getter setter in a c++ class
Question
Okay, I have something like this in C++:
class MyClass{
private:
int someVariable;
int someOtherVariable;
struct structName{
int someStructVariable;
int someOtherStructVariable;
};//end of struct
public:
//getters & setters for the defined variables.
int getSomeStructVariable()
{
// this does not work I get this error: "error: expected primary-expression
// before '.' token"
return structName.someStructVariable;
}
};//end of class
How should I write my getter or setter in this case?
Solution
structName
is part of the type name, not the variable name. You need to give it a name, something like:
struct structName {
int someStructVariable;
int someOtherStructVariable;
} myStructure;
And then in your accessor use:
return myStructure.someStructVariable;
That should get you the result you want. Other alternatives for the structure variable are to separate out the structure definition from the variable declaration:
struct structName {
int someStructVariable;
int someOtherStructVariable;
};
struct structName myStructure;
or to add in typedef
:
typedef struct structName {
int someStructVariable;
int someOtherStructVariable;
} structTypedefName;
structTypedefName myStructure;
OTHER TIPS
struct A {
A() : _n(0) {}
int get_n() const {
return _n;
}
void calculate(int a) {
_n = a * a * a;
}
private:
int _n;
};
Here's a complete example. If you want a mirror set_n
instead of something which manipulates the data, then you should probably drop the getter/setter (as you'd be using them incorrectly) and make the data member public.
Also, remember: defining classes with struct
works identically to defining classes with class
but for one exception: public instead of private as the default access for members and bases.
It is not a good idea to write a getter/setter for each structure field. A better solution is:
typedef struct {
int field1;
int field2;
} structType;
class MyClass {
private:
structType _structName;
public:
const structType & getStructName() const {
return _structName;
}
}
Keep structType
and MyClass
separate. Use the getter as:
MyClass m;
int var;
var = m.getStructName().field1;
The first const
is needed to return a const value. The second one is needed for const-correctness.
There are two ways to define a setter:
class MyClass {
// ...
public:
// type 1
void setStructName(const structType &s) {
_structName = s;
}
// type 2
structType & setStructName() {
return _structName;
}
}
Use the first one as:
MyClass m;
structType s;
m.setStructName(s);
The second version enables you to modify separate structure fields as well:
m.setStructName() = s;
m.setStructName().field1 = 10;
Note that the setter might need some adjustments if the structure contains pointers.