1

この質問への答えは本当に簡単だと思いますが、これを正しく機能させることができません。基本的に 2 つのクラスを作成しました。1 つはポイント用で、もう 1 つはポリゴン用です。Polygons は、ポイントの動的リストで構成されます。

ただし、ポイント クラスで + 演算子をオーバーロードして 2 つのポイントのポリゴンを返そうとすると、コンソール ウィンドウを閉じた後に奇妙な出力と「デバッグ アサーションに失敗しました」というメッセージが表示されます。

+ 演算子のオーバーロード メソッドは次のとおりです。

CPolygon CPoint::operator + (CPoint pointToAdd) {
    CPolygon polygon;
    polygon.addPoint(this);
    polygon.addPoint(pointToAdd);

    cout << polygon.toString();

    return polygon;
}

このメソッドを使用しようとすると、たとえば次の出力が得られます。

(5, 2, 3) - (1, 1, 2)

(444417074, -33686019, , -1555471217) - (-1424299942, 0, 0)

出力された最初の行はメソッド自体からのものですが、2 番目の行はポリゴンが返される場所からのものです。

メソッドの内部から呼び出し元のコードに戻る途中で、ポリゴン オブジェクトに何が起こっているのか、私にはまったくわかりません。

誰かが私にこれについて少し洞察を与えることができれば、私は非常に感謝しています:)

編集

次に、ポリゴン クラスの addPoint メソッドを示します。

void CPolygon::addPoint(CPoint pointToAdd) {
    nrOfPoints++;

    // Create a temp array of the new size
    CPoint * tempPoints = new CPoint[nrOfPoints];

    // Copy all points to the temp array
    for(int i = 0; i < (nrOfPoints - 1); i++) {
        tempPoints[i] = points[i];
    }

    // Add the new point to the end of the array
    tempPoints[nrOfPoints - 1] = pointToAdd;

    // Delete the old array and set the temp array as the new array
    delete[] points;
    points = tempPoints;
}

void CPolygon::addPoint(CPoint * pointToAdd) {
    addPoint(* pointToAdd);
}
4

3 に答える 3

0

あなたのコード:

CPolygon CPoint::operator + (CPoint pointToAdd) {
    CPolygon polygon;


    polygon.addPoint(this);
    polygon.addPoint(pointToAdd);

    cout << polygon.toString();

    return polygon;
}

はポインターであるため、polygon.addPoint(this)にポインターを追加しているのは奇妙に 思えます。代わりに使用する必要がありますか?値または参照によって追加しています。CPolygonthispolygon.addPoint(*this)polygon.addPoint(pointToAdd)

さらにヘルプが必要な場合は、 function のすべてのプロトタイプを追加してくださいCPolygon::addPoint

于 2013-10-09T09:16:46.437 に答える
-1

ポリゴン オブジェクトはスタック上で宣言されています。オペレータ スコープの後で、ポリゴン オブジェクトへの参照が失われます。

それを宣言してみてください:

CPolygon* polygon = new Polygon(...);

署名は次のようになります。

CPolygon* CPoint::operator + (CPoint pointToAdd) 

実際、生のポインターを使用するのは悪い考えであり、スコープ外で処理する必要があります。より良い解決策は、スマートポインターを使用することです。

std::auto_ptr<CPolygon> CPoint::operator + (CPoint pointToAdd) 
{
    std::auto_ptr<CPolygon> polygon(new CPolygon);
    // do stuff here
    return polygon;
}

// ...

{
  std::auto_ptr<CPolygon> polygon = firstPoint + secondPoint;
  // working with CPolygon

  // auto_ptr frees polygon 
}
于 2013-10-09T09:30:17.123 に答える