代码如下:
//抽象类,异常基类,不能被实例化。
class BaseMyException {
public:
virtual void what() = 0;//纯虚函数
virtual ~BaseMyException(){}
};
//目标类为空
class TargetSpaceNullException :public BaseMyException {
public:
virtual void what() {
cout << "目标空间为空!" << endl;
}
~TargetSpaceNullException() {};
};
//源类为空
class SourceSpaceNullException :public BaseMyException {
public:
virtual void what() {
cout << "源空间为空!" << endl;
}
~SourceSpaceNullException() {};
};
void copy(char* target, char* source) {
if (target == nullptr) {
throw TargetSpaceNullException();
}
if (source == nullptr) {
throw SourceSpaceNullException();
}
for (int i = 0; source[i] != '\0'; i++) {
target[i] = source[i];
}
}
int main() {
char s[64] = "abcdefg";
char* source = s;
char str[1024]={'\0'};
try {
copy(str, source);
}
catch (BaseMyException& e) {//抽象类不能被实例化。
e.what();
}
cout << str << endl;
}
结果:
修改代码:
copy(nullptr, source);
结果
修改代码:
copy(str, nullptr);
结果: