질문이 적절하지는 않지만 최선을 다할 것입니다.상속 된 클래스에 생성자가 없을 때 예외를 throw하는 방법은 무엇입니까?
이것은 숙제 문제입니다. 숙제는 두 줄이 평행하거나 같으면 예외를 던져달라고 부탁합니다.
원래 코드는 내 교수가 제공하고 나의 일은 예외를 던질 수 있도록 수정하는 것입니다.
line.h
class RuntimeException{
private:
string errorMsg;
public:
RuntimeException(const string& err) { errorMsg = err; }
string getMessage() const { return errorMsg; }
};
class EqualLines: public RuntimeException{
public:
//empty
};
class ParallelLines: public RuntimeException{
public:
//empty
};
class Line{
public:
Line(double slope, double y_intercept): a(slope), b(y_intercept) {};
double intersect(const Line L) const throw(ParallelLines,
EqualLines);
//...getter and setter
private:
double a;
double b;
};
교수는 .cpp 파일이 약간 변형 될 수 있으며, 헤더 파일을 수정하지 우리에게 말했다.
line.cpp 두 상속 클래스 이후
double Line::intersect(const Line L) const throw(ParallelLines,
EqualLines){
//below is my own code
if ((getSlope() == L.getSlope()) && (getIntercept() != L.getIntercept())) {
//then it is parallel, throw an exception
}
else if ((getSlope() == L.getSlope()) && (getIntercept() == L.getIntercept())) {
//then it is equal, throw an exception
}
else {
//return x coordinate of that point
return ((L.getIntercept()-getIntercept())/(getSlope()-L.getSlope()));
}
//above is my own code
}
는 따라서 errorMsg
를 초기화하는 생성자 비어 없으며, 나는 예외를 던져 그 클래스의 객체를 생성 할 수 있습니다. 이것을 달성하기위한 대안?
게시 한 코드는 이전의 'throw'사양을 사용합니다. 그것들을 버리고 새롭고 현대적인'noexcept' 지정자를 사용하여 함수가 아무것도 던지지 않는지, 그리고 아무 것도하지 않는 것을 고려하십시오. 귀하의 경우에는 더 이상이 오래된 기법을 사용하지 말 것을 교수에게 알려주십시오 – Rakete1111
* 교수가 헤더 파일을 수정하지 말 것을 권고했지만 .cpp 파일 만 수정할 수 있습니다. * 교수님은 사용자 정의 예외가 'std :: exception'에서 파생됩니다. 즉,'RuntimeException : public std :: exception {...};' – PaulMcKenzie
@PaulMcKenzie'std :: exception'에서 왜 파생되어야합니까? – 0x499602D2