1

私は C++ の初心者です (Java から来ました)。次のコードがあります。

//#include <boost/algorithm/string.hpp>
#include <iostream>
#include <math.h>
#include <vector>
#include <string.h>
#include <string>
#include <bitset>
#include <algorithm>
#include <sstream>
#include <memory>
#include <assert.h>
#include <cctype>

using namespace std;

class Point{
private:
    int x;
    int y;
public:
    Point(int x,int y){
        this->x=x;
        this->y=y;
    }

    int getX(){
        return x;
    }

    int getY(){
        return y;
    }

    operator const char*(){
        return toString().c_str();
    }

    string toString(){
        ostringstream stream;
        stream<<"( "<<x<<", "<<y<<" )";
        return stream.str();
    }
};


class Line{
private:
    Point p1=Point(0,0);
    Point p2=Point(0,0);

public:
    Line(Point p1, Point p2){
        this->p1=p1;
        this->p2=p2;
    }

    Point getP1(){
        return p1;
    }

    Point getP2(){
        return p2;
    }

    operator const char*(){
        ostringstream stream;
        stream<<"[ "<<p1<<" -> "<<p2<<" ]";
        return stream.str().c_str();
    }

    //    operator const char*(){
    //        ostringstream stream;
    //        stream<<"[ "<<p1<<" -> ";
    //        stream<<p2<<" ]";
    //        return stream.str().c_str();
    //    }
};

int main()
{

    Line line=Line(Point(1,2), Point(3,4));
    cout<<line<<endl;


    cout<<"\nProgram exited successfully."<<endl;
    return 0;
}

cout< を使用できるように、演算子 const* を再定義しました。

しかし、2番目のブロックをコメントアウトして(演算子const *の2つのバージョンがあり、デフォルトでは2番目のブロックがコメントアウトされています)、プログラムをそのまま実行すると、表示されます

[ (1, 2) -> (1, 2) ]

しかし、2 番目のブロックをコメント解除して実行すると、出力は期待どおりになります。

[ (1, 2) -> (3, 4) ]

この問題は、両方の Point オブジェクトを同じ行に表示すると発生するようです (連鎖のようなものですが、ここで連鎖が正しい言葉であるかどうかはわかりません)。

私の質問は、なぜこれが起こっているのですか?

アップデート

std::ostream& operator << 関数を Line クラスに追加しましたが、次のエラーが表示されます。

/home/ryu/qt_workspace/hello/main.cpp:67: error: 'std::ostream& Line::operator<<(std::ostream&, const Line&)' must take exactly one argument

/home/ryu/qt_workspace/hello/main.cpp:77: error: cannot bind 'std::ostream {aka std::basic_ostream<char>}' lvalue to 'std::basic_ostream<char>&&'

よろしく、アウレリアン

4

2 に答える 2

2

を使用する場合cout <<は、より直接的な方法があります。

この関数を に追加しますLine

friend std::ostream& operator << ( std::ostream & os, const Line & l ){
    os << "[ " << l.p1 << " -> " << l.p2 << " ]";
    return os;
}

また、あなたのアプローチが無効なメモリを返していたことにも注意してください。これは、Java が C++ と大きく異なる点です。

    return stream.str().c_str();  // Danger!

streamで宣言され、operator const char*()その有効期間をその関数に制限します。そのスコープを出ると破棄されます。その結果、もはや存在しないものへのポインタを返しています。

于 2013-06-03T20:08:35.630 に答える
0

実際には、C++ 11 では文字列を値で返すことはまったく問題ないと思うので、下の cstring を使用する代わりに、そこで転送を行うことができます。

移動セマンティクスとは

于 2013-06-03T20:57:36.227 に答える