09/03/30 22:21:29
継承した親クラスの実体を参照するメンバ変数を、なるべく無駄なメモリを消費せずに
実現したいのですが、よい方法はないでしょうか?
メンバ関数を使えばよいのは承知しているのですが、できれば "()" を書かずに済ませたいのです
struct coord { int x; int y; } ///< これを親にしたい
class state {
coord position; ///< この部分をメンバ変数として持つのではなく親から継承したい
coord velocity;
void foo();
}
extern void bar(coord& param);
void state::foo() { bar(position); bar(velocity); }
現在は親の参照を返すメソッドを作り、マクロでごまかして無理矢理実現しています
しかしマクロがソース全域に作用してしまうのでなんとかしたいのです
class state: public coord {
coord velocity;
coord& position() { return *this; } ///< 参照を追加
const coord& position() const { return *this; } ///< const 参照を追加
#define position position() ///< 強引にマクロ…関係ない部分まで作用してしまうのが難点
void foo(); ///< foo() 内で親の実体を *this ではなく position と書いてアクセスしたい!
}
試しにこんな風に書いてみたのですが、うまくいきませんでした
class state: public coord {
coord velocity;
const coord& position; /// こんな感じの参照をメモリ消費なしで定義したい
state(): position(*this) {} /// ここでエラー orz
void foo();
}