我想重載運算符<<
,因此可以使用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