Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/124.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 您可以基于对象隐式调用方法吗_C++ - Fatal编程技术网

C++ 您可以基于对象隐式调用方法吗

C++ 您可以基于对象隐式调用方法吗,c++,C++,我为正在处理的类编写了一个to_string()方法。它应该与操作符重载一起用于打印类对象。但如果我这样做: std::ostringstream oss; oss << Jd(0.5); BOOST_CHECK_EQUAL( oss.str(), std::string("JD 0.5") ); std::ostringstream oss; oss您应该重载流插入操作符(您需要重写操作符 std::string Jd::to_string() const { ostr

我为正在处理的类编写了一个to_string()方法。它应该与操作符重载一起用于打印类对象。但如果我这样做:

std::ostringstream oss;
oss << Jd(0.5);
BOOST_CHECK_EQUAL( oss.str(), std::string("JD 0.5") );
std::ostringstream oss;

oss您应该重载流插入操作符(
您需要重写
操作符
std::string Jd::to_string() const {

    ostringstream oss;
    oss << "JD " << jd_;
    return oss.str();
} 
class Jd
{
friend std::ostream& operator<<(std::ostream&, const Jd&);
};

std::ostream& operator<<(std::ostream& out, const Jd& obj)
{
   out << "JD " << obj.jd_;
   return out;
}
std::ostringstream& operator<<(std::ostringstream& os, const Jd& jd)
{
  os << jd.to_string();
  return os;
}