accedere alla variabile struct all'interno del setter getter in una classe c ++
Domanda
Okay, ho qualcosa del genere 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
Come devo scrivere il mio getter o setter in questo caso?
Soluzione
structName
fa parte del nome del tipo, non del nome della variabile. Devi dargli un nome, qualcosa del tipo:
struct structName {
int someStructVariable;
int someOtherStructVariable;
} myStructure;
E poi nel tuo accessore usa:
return myStructure.someStructVariable;
Questo dovrebbe darti il ??risultato che desideri. Altre alternative per la variabile struttura sono di separare la definizione della struttura dalla dichiarazione della variabile:
struct structName {
int someStructVariable;
int someOtherStructVariable;
};
struct structName myStructure;
o per aggiungere in typedef
:
typedef struct structName {
int someStructVariable;
int someOtherStructVariable;
} structTypedefName;
structTypedefName myStructure;
Altri suggerimenti
struct A {
A() : _n(0) {}
int get_n() const {
return _n;
}
void calculate(int a) {
_n = a * a * a;
}
private:
int _n;
};
Ecco un esempio completo. Se vuoi un mirror set_n
invece di qualcosa che manipola i dati, allora dovresti probabilmente eliminare il getter / setter (poiché li utilizzeresti in modo errato) e rendere pubblico il membro dei dati.
Inoltre, ricorda: la definizione di classi con struct
funziona in modo identico per la definizione di classi con class
ma per un'eccezione: public anziché private come il accesso predefinito per membri e basi.
Non è una buona idea scrivere un getter / setter per ogni campo della struttura. Una soluzione migliore è:
typedef struct {
int field1;
int field2;
} structType;
class MyClass {
private:
structType _structName;
public:
const structType & getStructName() const {
return _structName;
}
}
Mantieni structType
e MyClass
separati. Usa il getter come:
MyClass m;
int var;
var = m.getStructName().field1;
La prima const
è necessaria per restituire un valore const. Il secondo è necessario per const-correctness .
Esistono due modi per definire un setter:
class MyClass {
// ...
public:
// type 1
void setStructName(const structType &s) {
_structName = s;
}
// type 2
structType & setStructName() {
return _structName;
}
}
Usa il primo come:
MyClass m;
structType s;
m.setStructName(s);
La seconda versione consente anche di modificare campi di struttura separati:
m.setStructName() = s;
m.setStructName().field1 = 10;
Nota che il setter potrebbe aver bisogno di alcune modifiche se la struttura contiene puntatori.