One と Two の 2 つのクラスがあるとします。One と Two は本質的に同じですが、Two は One に変換できます。
#ifndef _ONE_H_
#define _ONE_H_
class One
{
private:
float m_x;
float m_y;
public:
One();
One(float x, float y);
};
#endif
#ifndef _TWO_H_
#define _TWO_H_
#include "One.h"
class Two
{
private:
float m_x;
float m_y;
public:
Two();
Two(float x, float y);
operator One() { return One(m_x, m_y); }
operator One* () { return &One(m_x, m_y); }
operator One& () const { return *this; }
float GetX(void) { return m_x ;}
float GetY(void) { return m_y ;}
void Print();
};
#endif
Two は One にアクセスできますが、One は Two にアクセスできません。main.cpp には次のものがあります。
One a(4.5f, 5.5f);
Two b(10.5, 7.5);
One * c = &b;
One のポインタを Two のアドレスにしようとすると、エラーが発生します。エラーは「エラー C2440: '初期化中': 'Two *' から 'One *' に変換できません」です。
それが可能であるとしても、私は一生これを行う方法を理解することはできません。どんな助けでも大歓迎です。
編集: で Two.h に新しい行を追加しましたoperator One& () const { return *this; }
。この変換演算子を機能させるために使用しようとしている関数は次のとおりですvoid TestRefConstPrint(const One &testClass);
。以下のメインでは、「パラメータ 1 を Two から変換できません」という新しいエラーが表示されます。
メインの中で私は:
int main()
{
Two b(10.5, 7.5);
TestRefConstPrint(b);
return 0;
}