ダブルポインタの扱い

using namespace std;

struct Hoge final
{
public:
    int a;
};

int main()
{
    vector<Hoge*> v1;
    Hoge* hoge = new Hoge();
    v1.push_back(hoge);

    for (auto it = v1.begin(); it != v1.end();){
        *it->a = 3;
        it++;
    }
}

というコードを実行したら、「error: member reference base type ‘Hoge *’ is not a structure or union」と表示されて謎だったが、下記のように()で囲む必要があった。

using namespace std;

struct Hoge final
{
public:
    int a;
};

int main()
{
    vector<Hoge*> v1;
    Hoge* hoge = new Hoge();
    v1.push_back(hoge);

    for (auto it = v1.begin(); it != v1.end();){
        (*it)->a = 3;
        it++;
    }
}

https://freebsd.sing.ne.jp/lang/c/11/03.html

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です