views:

281

answers:

2

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?

+7  A: 

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;
Carl Norum
Beat me to it. +1
Marcin
No need for typedef to drop the struct class-key, `struct Name {}; Name variable;` works fine.
Roger Pate
O RLY? I'm not a C++ guy, I'm afraid. C definitely requires the `typedef`. I guess it makes sense; C++ doesn't require the `class` keyword to be around when you declare instances either.
Carl Norum
+1  A: 
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.

Roger Pate
Now that someone has kindly edited the code, I see I've misread the problem. (D'oh.) Going to leave the answer up anyway.
Roger Pate