質問

さて、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

この場合、ゲッターまたはセッターをどのように書くべきですか?

役に立ちましたか?

解決

structName は変数名ではなく型名の一部です。次のような名前を付ける必要があります。

struct structName {
  int someStructVariable;
  int someOtherStructVariable;
} myStructure;

そして、アクセサで次を使用します:

return myStructure.someStructVariable;

これにより、目的の結果が得られます。構造変数の他の代替方法は、変数宣言から構造定義を分離することです:

struct structName {
  int someStructVariable;
  int someOtherStructVariable;
};

struct structName myStructure;

または typedef に追加する:

typedef struct structName {
  int someStructVariable;
  int someOtherStructVariable;
} structTypedefName;

structTypedefName myStructure;

他のヒント

struct A {
  A() : _n(0) {}
  int get_n() const {
    return _n;
  }
  void calculate(int a) {
    _n = a * a * a;
  }
private:
  int _n;
};

これは完全な例です。データを操作するものの代わりにミラー set_n が必要な場合は、おそらくゲッター/セッターを(誤って使用するため)ドロップし、データメンバーをパブリックにする必要があります。

また、覚えておいてください: struct を使用してクラスを定義すると、同一 class を使用してクラスを定義しますが、1つの例外があります:メンバーとベースのデフォルトアクセス。

構造フィールドごとにゲッター/セッターを作成することはお勧めできません。より良い解決策は次のとおりです。

typedef struct {
    int field1;
    int field2;
} structType;

class MyClass {
private:
    structType _structName;
public:
    const structType & getStructName() const {
        return _structName;
    }
}

structType MyClass を別々にします。ゲッターを次のように使用します。

MyClass m;
int var;
var = m.getStructName().field1;

const値を返すには、最初の const が必要です。 2番目は const-correctness に必要です。

セッターを定義するには2つの方法があります:

class MyClass {
// ...
public:
    // type 1
    void setStructName(const structType &s) {
        _structName = s;
    }
    // type 2
    structType & setStructName() {
        return _structName;
    }
}

最初のものを次のように使用します。

MyClass m;
structType s;
m.setStructName(s);

2番目のバージョンでは、個別の構造体フィールドも変更できます:

m.setStructName() = s;
m.setStructName().field1 = 10;

構造体にポインターが含まれる場合、セッターは調整が必要になる場合があることに注意してください。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top