ここでかなり具体的な質問!
惑星に関するデータを保持するクラスがあります。たとえば、位置を保持するベクトル (double x、double y、double z) や、半径を保持する double 変数などがあります。
私はよく参照を使用して、プライベート変数への「読み取り専用パブリック アクセス」を取得します。プライベート変数を変更するセッター メソッドを呼び出します。
ただし、これはベクトルやリストなどの動的コンテナー内では許可されていないと思います。
私は「定数定数」ポインターを試しました。アイデアは初期化リストで初期化されると、他のものを指すことも変数を変更することもできなくなります。ただし、コンパイル時に同じエラー メッセージが表示されます。
メッセージは次のとおりです:「エラー: 非静的 const メンバーconst double* const x
、デフォルトの代入演算子を使用できません」
それで、「push_back」をベクターに実行するときにクラスをコピーすると問題が発生します。
コード例を次に示します。
class planet{
private:
double _radius;
public:
// Constructor
planet() : rad(_radius){
_radius = 0.0f;
}
// This is a setter method - works fine
void setrad(double new_rad){
_radius = rad;
}
// This is a better solution to the getter method
// - does not seem to work with dynamic containers!
const double& rad; // This is initialized in the constructor list
};
int main(...){
...
std::vector<planet> the_planets;
planet next_planet_to_push;
next_planet_to_push.setrad(1.0f);
// This causes the error!
the_planets.push_back(next_planet_to_add);
...
}