Code Fix

中級

error: is private within this context の原因と直し方

private指定されたクラスのメンバ変数に、クラスの外から直接アクセスしようとしたときに出るエラーです。カプセル化のためにprivateメンバは外部から直接触れないようになっています。

エラーメッセージの読み方

main.cpp:8:7: error: 'int Account::balance' is private within this context
main.cpp
ファイル名
8
行番号
7
列番号 — この位置でg++が構文解析に失敗しました
'int Account::balance' is private within this context
内容 — 期待していたもの、または受け付けられなかったもの

このエラーが出る典型パターン

パターン1

 1  #include <iostream>
 2  class Account {
 3  private  :
        ^
 4      int balance = 0;
 5  };
 6  int main() {
 7      Account a;
 8      a.balance = 100;
 9      std::cout << "done" << std::endl;
10      return 0;
11  }
main.cpp:8:7: error: 'int Account::balance' is private within this context

balanceはprivateなので、クラスの外にあるmain関数から直接触ることはできません。外部から操作させたいならpublicにする必要があります。

直し方: privatepublic にします。

この問題を解いてみる →

広告
広告スロット(未設定)

パターン2

 1  #include <iostream>
 2  class Robot {
 3  private  :
        ^
 4      int power = 0;
 5  };
 6  int main() {
 7      Robot r;
 8      r.power = 50;
 9      std::cout << "done" << std::endl;
10      return 0;
11  }
main.cpp:8:7: error: 'int Robot::power' is private within this context

アクセス制御はインスタンスの有無ではなく、コードがクラスの内側かどうかで決まります。

直し方: privatepublic にします。

この問題を解いてみる →

パターン3

 1  #include <iostream>
 2  class Wallet {
 3  private  :
        ^
 4      int coins = 0;
 5  };
 6  int main() {
 7      Wallet w;
 8      w.coins = 20;
 9      std::cout << "done" << std::endl;
10      return 0;
11  }
main.cpp:8:7: error: 'int Wallet::coins' is private within this context

本来はゲッター・セッターを用意してカプセル化を保つのが望ましいですが、ここではpublicにすることでエラーの原因だけを直しています。

直し方: privatepublic にします。

この問題を解いてみる →

よくある誤解

「クラスのインスタンスを持っていればどのメンバにもアクセスできる」というのは誤解です。C++のアクセス制御はインスタンス単位ではなく、コードがそのクラスの内側にあるかどうかで決まります。外部から操作したいならpublicなメソッド(ゲッター・セッター)を用意する必要があります。

まとめ

error: is private within this contextは中級でつまずきやすい項目です。上の3パターンを実際に手で直すと、エラーメッセージのどこを読めばよいかが掴めます。

演習をはじめる

関連するエラー

広告
広告スロット(未設定)