我是 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;
}
我重新定义了运算符 const* 以便我可以使用 cout<
但是,如果我现在运行程序,将第二个块注释掉(我有两个版本的 operator const*,默认情况下第二个被注释掉),它将显示
[ (1, 2) -> (1, 2) ]
但是在第二个块未注释的情况下运行时,输出如预期:
[ (1, 2) -> (3, 4) ]
当我在同一行中显示两个 Point 对象时似乎会出现问题(某种链接,尽管我不知道链接是否是正确的词)
我的问题是,为什么会这样?
更新
我已将 std::ostream& 运算符 << 函数添加到我的 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>&&'
问候, 奥勒良