Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/157.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++ OSTREAM将常量字符串解释为指针_C++_Strstream - Fatal编程技术网

C++ OSTREAM将常量字符串解释为指针

C++ OSTREAM将常量字符串解释为指针,c++,strstream,C++,Strstream,我在清理旧C/C++应用程序的调试宏时遇到了这个问题:我们有一个从ostream继承的跟踪类(我知道它从C++98开始就被弃用了,但这个应用程序是在1998年编写的!),我们这样使用它: Tracer() << "some" << " message" << " here"; 首先要注意的是,操作符是这样工作的,因为Tracer()是一个临时的(右值),不能绑定到操作符库中的非常量引用以进行解释。。。但是,我该如何解决这个问题?有没有比预先编写更好的方法谢谢

我在清理旧C/C++应用程序的调试宏时遇到了这个问题:我们有一个从
ostream
继承的跟踪类(我知道它从C++98开始就被弃用了,但这个应用程序是在1998年编写的!),我们这样使用它:

Tracer() << "some" << " message" << " here";

首先要注意的是,
操作符是这样工作的,因为
Tracer()
是一个临时的(右值),不能绑定到
操作符库中的非常量引用以进行解释。。。但是,我该如何解决这个问题?有没有比预先编写
更好的方法谢谢,这是实现它的最好方法。。。但不确定我们是否会使用它,因为实际的类更大、更复杂,我们的政策是对代码进行尽可能少的更改-该应用程序已经有15年的历史了(Ostream当时还没有被弃用^^^),大多数开发人员早就离开了公司,因此,如果我们破坏了我们所做的事情:/@l4mpi:single
operatorhanks以获取解释-请参阅我对nawaz答案的评论,对此最好的解决方法是什么?不,标准方法是执行类似
Tracer()的操作好的,谢谢。所讨论的编译器是g++4.1.2 RedHat,很遗憾它不符合c++11…@l4mpi:不要使用
std::ostream
。它已被弃用。也不要从流类派生。在这种情况下,构图更好。编写一个包装器类,如我的答案所示。
#include <strstream>
#include <iostream>

using namespace std;

class Trace : public ostrstream {
    public:
        Trace();
        virtual ~Trace();
};

Trace::Trace() : ostrstream() {}
Trace::~Trace() {
    static_cast< ostrstream& >(*this) <<ends;
    char * text = ostrstream::str();
    cout << "MESSAGE: "<< text <<endl;
    delete[] text;
}

int main(){
    Trace() << "some" << " text" << " here";
    Trace() << left << "some" << " text" << " here";
    Trace() << 123 << " text" << " here";
}
#include <sstream> //for std::ostringstream

struct Trace
{
   std::ostringstream ss;

   template<typename T>
   Trace& operator << (T const & data)
   {
        ss << data;
        return *this;
   }
   ~Trace()
   {
       std::cout << ss.str() << std::endl;
   }
};
Trace() << "Hello World\n" << 100 << "\nBye\n";
Hello World
100
Bye