0

クラス CustomerNode の 2 つのオブジェクトを比較し、これらのメソッドのアルファベット順の優位性に関連する結果を返そうとしています。これが機能しない理由を正確に理解することはできません。私には、論理は適切に見え、宿題の指示に従っています。

    bool OrderedList::add (CustomerNode* newEntry)
{
if (newEntry != 0)
{
    CustomerNode * current;
    CustomerNode * previous = NULL;
    if(!head)
        head = newEntry;
    current = head;
  // initialize "current" & "previous" pointers for list traversal
   while(current && *newEntry < *current) // location not yet found (use short-circuit evaluation)
   {
    // move on to next location to check
    previous = current;
    current = current->getNext();
   }

  // insert node at found location (2 cases: at head or not at head)
  //if previous did not acquire a value, then the newEntry was
  //superior to the first in the list. 
  if(previous == NULL)
    head = newEntry;
  else
  {
    previous->setNext(newEntry); //Previous now needs to point to the newEntry
    newEntry->setNext(current); //and the newEntry points to the value stored in current.
  }
}
    return newEntry != 0;  // success or failure
    }

さて、プログラムに含まれるオーバーロードされた operator< を次に示します。汎用オブジェクトでテストすると、期待どおりの結果が得られます。

    bool CustomerNode::operator< (const CustomerNode& op2) const
    {
       bool result = true;
       //Variable to carry & return result
       //Initialize to true, and then:
       if (strcmp(op2.lastName, lastName))
        result = false;

        return result;
       }

私はプログラミングに非常に慣れていないので、まだ学んでいるので、特にスタイルの批評など、どんな回答にも感謝します。私のロジックが間違っているだけですか、それとも他に注意する必要があるルールはありますか? パラメーターが参照である理由、またはオペレーターを呼び出すために実際にパラメーターを逆参照する必要があるかどうかを完全には理解していません。

ありがとう。

4

1 に答える 1

2

あなたの状態は間違っています:

if (strcmp(op2.lastName, lastName))

異なる文字列の場合、順序に関係なく、これは not- false(true) を返し、関数は を返しfalseます。

正しい条件は次のとおりです。

if (strcmp(op2.lastName, lastName) >= 0)

または、すべてを書き直すこともできます。

bool CustomerNode::operator< (const CustomerNode& op2) const
{
   return  strcmp(op2.lastName, lastName) < 0;
}
于 2012-10-02T10:39:08.147 に答える