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는 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 번 줄에 있다고 생각합니다. : return os << E.operator const char *() main.cpp의 17 행에 eprinted 될 때 : cout << T << endl; – elvisi27