라이브러리를 만들고 있습니다. 고정 길이 문자열 클래스를 만들고 싶습니다.예외 예외 대 결과 코드 반환
#include <string>
#include <iostream>
#define OK 0
#define TOO_LONG 1
#define UNALLOWED_CHARACTERS 2
struct MyString {
MyString(int l)
: m_length(l) { }
struct exception {
exception(int t, MyString *p)
: type(t), ptr(p) { }
int type;
MyString *ptr;
};
int set(const std::string& name);
void set2(const std::string& name) throw(exception);
std::string m_str;
int m_length;
};
int MyString::set(const std::string& s)
{
if(s.size() > 64) {
return TOO_LONG;
} else if(s.find('~') != std::string::npos) {
return UNALLOWED_CHARACTERS;
} else {
m_str = s;
return OK;
}
}
void MyString::set2(const std::string& s) throw(exception)
{
if(s.size() > m_length) {
throw exception(TOO_LONG, this);
} else if(s.find('~') != std::string::npos) {
throw exception(UNALLOWED_CHARACTERS, this);
} else {
m_str = s;
}
}
int main()
{
using namespace std;
//OPTION 1
{
MyString s1(10);
MyString s2(10);
int code;
code = s1.set("abcdefghijX");
switch(code) {
case TOO_LONG:
//handle <--
break;
case UNALLOWED_CHARACTERS:
//handle
break;
default:
//ok!
break;
}
code = s2.set("abcdefghi~");
switch(code) {
case TOO_LONG:
//handle
break;
case UNALLOWED_CHARACTERS:
//handle <--
break;
default:
//ok!
break;
}
}
//OPTION 2
{
MyString s1(10);
MyString s2(10);
try {
s1.set2("abcdefghijX");
s2.set2("abcdefghi~");
} catch(MyString::exception &e) {
cerr << "MyString::exception: ";
auto p = e.ptr;
if(p == &s1) cerr << "s1 ";
else if(p == &s2) cerr << "s2 ";
switch(e.type) {
case TOO_LONG: cerr << "too long"; break;
case UNALLOWED_CHARACTERS: cerr << "unallowed characters"; break;
}
cerr << endl;
}
}
}
어떤 버전의 MyString :: set()을 사용해야할지 모르겠다. 그러한 경우 국제 대회는 무엇입니까? 이 예제에서는 데모 용으로 STL을 사용했습니다.
이것은 표면 상으로 큰 질문이지만 실제로 많은 논쟁을 이끌어 낼 것입니다. 그 종교적인 문제 중 하나입니다. – djechlin
또한 throw 사양을 사용하지 마십시오. 내가 바꿀 수있는 것은 바보 같은 이유들이 런타임에 검사되어 std :: unexpected로 이어질 것이고 따라서 위반된다면 (디버그/개발 설정에서는 유용하지만 프로덕션 환경에서는 유용하지 않다.) 말 그대로 반대로 당신이 예외를 원한다. – djechlin
@djechlin 좋은 지적. 또한 예외 사양은 C++ 11에서 사용되지 않습니다. – juanchopanza