私は 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>&&'
よろしく、アウレリアン