C++検索レコードとキーの比較

1013 ワード

コンパイルしたばかりで、メンバー関数の操作に問題はありません.ここでは主にレコードとキーの比較的有名な実装を覚えています.
先生がくれたPPTには2つの実現方法があります.
1.operator T()暗黙変換でRecordをKeyに変換
class Record{
public:
	operator Key( ); // Record to Key       .
	Record(int x=0, int y=0);
private:
	int key;
	int other;
};

Record::operator Key( ){
	Key tmp(key);
    return tmp;
}

ここでのTは変換するタイプであり,我々の例ではKeyであり,RecordをKeyタイプに変換する.
実装関数のtmpはKeyタイプの値であり、tmpを初期化する.キーはrecordです.キーの値を返し、キータイプの変数を返してレコードをキーに変換します.
2.Keyによるコピーコンストラクタ
class Key {
	int key;
public:
	Key (int x = 0);
	Key (const Record &r);
	int the_key( ) const;
};

bool operator == (const Key &x, const Key &y);

Key::Key(const Record &r){
	key=r.the_key();
}

class Record{
public:
	Record(int x=0, int y=0);
	int the_key() const;
private:
	int key;
	int other;
};

int Record::the_key() const{
	return key;
}

正直に言うと、この方法は少し迂回しているように見えます.
コアは、キー(const Record&r)を呼び出す、一時的にキーtmpを構築する.key=r.key、その後==比較でkeyクラスの構造関数を呼び出してtmpを解放します.