我想重载运算符<<
,因此可以使用cout
打印错误。我需要打印m_messag
指出的c-string
e。谁能帮我解决这个问题吗?在ostream中使用运算符const char *
My Error.h
头:
ifndef ICT_ERROR_H_
#define ICT_ERROR_H_
#include <iostream>
namespace ict {
class Error {
char* m_message;
public:
// constructors
Error();
Error(const char* errorMessage);
// destructor
virtual ~Error();
// deleted constructor and operator=
Error(const Error& em) = delete;
Error& operator=(const Error& em) = delete;
// operator= for c-style strings
void operator=(const char* errorMessage);
// methods
void clear();
bool isClear()const;
void message(const char* value);
// cast overloads
operator const char*() const;
operator bool()const;
};
// operator << overload prototype for cout
std::ostream& operator<<(std::ostream& os, const Error& E);
}
#endif
Error.cpp
#define _CRT_SECURE_NO_WARNINGS
#include <cstring>
#include "Error.h"
namespace ict{
Error::Error()
{
m_message = nullptr;
}
Error::Error(const char * errorMessage)
{
m_message = nullptr;
message(errorMessage);
}
Error::~Error()
{
delete[] m_message;
}
void Error::operator=(const char * errorMessage)
{
clear();
message(errorMessage);
}
void Error::clear()
{
delete[] m_message;
m_message = nullptr;
}
bool Error::isClear() const
{
bool status = false;
if (m_message==nullptr) {
status = true;
}
return status;
}
void Error::message(const char * value)
{
delete[] m_message;
m_message = new char[strlen(value)+1];
strcpy(m_message,value);
}
Error::operator const char*() const
{
return m_message;
}
Error::operator bool() const
{
return isClear();
}
***std::ostream& operator<<(std::ostream& os, const Error& E) {
if (E.isClear()) {
}
return os << E.operator const char *();
}***
}
Main.cpp
int main(){
Error T("Testing Error Message");
cout << T << endl ;
}
当我执行它,它提供了正确的输出,但它与下面的错误崩溃:
抛出异常:读取访问冲突。
_First was nullptr。
调试器:
static size_t __CLRCALL_OR_CDECL length(const _Elem *_First)
{ // find length of null-terminated string
//next statement to be executed ---> return (*_First == 0 ? 0
: _CSTD strlen(_First));
}
当您使用调试程序遍历代码时,调试程序声称发生了异常? –
@SamVarshavchik我很抱歉,我不是很熟悉Visual C++调试器,但它似乎指向我上面的调试器代码,而不是我的Error.cpp文件中的特定行 – elvisi27
@SamVarshavchik我认为问题是在第57行:当它在main.cpp的第17行上被打印时,返回os << E.operator const char *():cout << T << endl; – elvisi27