あなたが提供したコードには2つの大きな問題があります: 1。からへ
の変換を与えていません。2.プライベートと宣言されているため、 外部で
使用することはできません。struct coordstruct c
struct coordclass Model
struct coordとが似ているとしてもstruct c、コンパイラーの超能力は非常に限られています。コンパイラーの場合、2つの構造体は、本質的に同じであっても異なります。これを解決する1つの方法は、次struct cのタイプをとる適切な割り当て演算子を与えることstruct coordです。
strutc c {
...
void operator = (const coord& rhs) { ... }
};
外で使用するには、struct coordもっと公開する必要がありclass Modelます。
これを行うには、a)クラスModelの外部で宣言するか、
b
)クラスModelの内部でパブリックとして宣言します。struct coord
後者を行う場合はModel::coord、構造体にアクセスするために修飾名を使用する必要があります。
備考:
方法の変更を検討してください
coord Model::get() const;
に
const coord& Model::get() const;
大きな違いを生む微妙な変化。これにより、スタック上のの暗黙的な構築が保存struct coordされます。
演算子の変更を検討してください
void c::operator = (c &rhs);
に
void c::operator = (const c& rhs);
代入演算子は指定された引数structcを変更しないためです。
定数の正確さは、糖衣構文だけでなく必須であり、読みやすさを向上させます。
だからこれは私の提案です:
class Model {
public:
struct coord {
int x; int y;
};
private:
coord xy;
public:
const coord& get() const { return xy; }
};
struct c {
int x; int y;
void operator = (const c &rhs) { x = rhs.x; y = rhs.y; };
void operator = (const Model::coord &rhs) { x = rhs.x; y = rhs.y; };
};