- C++
override 什么意思
- 2025-6-8 16:09:16 @
#include <iostream>
#include <string>
#include <stdexcept>
#include <iostream>
using namespace std;
struct MyException : public exception {
private:
string message;
public:
MyException(const string& msg) : message(msg) {}
const char* what() const noexcept override {//重写
return message.c_str();
}
};
// 使用自定义异常
void checkAge(int age) {
if (age < 0) {
throw MyException("Invalid age: Age cannot be negative.");
}
}
int main() {
try {
checkAge(-15);
}
catch (MyException& e) {
cout << "自定义异常信息:" << e.what()<< endl;
}
cout << "程序正常结束!" << endl;
return 0;
}
override 什么意思
在C++中,override
是一个特殊的标识符,用于表明一个虚函数将重写基类中的对应函数。它主要有以下作用:
- 显式声明重写:告诉编译器这个函数是重写基类的虚函数,增强代码可读性。
- 编译时检查:确保重写的函数签名(名称、参数、常量性等)与基类完全一致。若不一致,编译器会报错。
在你的代码中的作用
在你的代码里:
const char* what() const noexcept override {
return message.c_str();
}
override
表明what()
函数重写了基类exception
中的虚函数。- 编译器会检查:
- 基类
exception
中是否有what()
函数。 - 函数签名是否匹配(返回类型、参数、常量性
const
、异常规范noexcept
)。
- 基类
为什么这里需要override
?
- 避免错误:如果不小心写错了函数签名(例如参数不同),没有
override
时编译器会认为这是一个新函数,而不是重写。使用override
后,编译器会报错,帮你发现问题。 - 代码清晰:明确告诉阅读代码的人:这个函数是故意重写基类的。
简单示例
假设基类有:
class Base {
public:
virtual void func() const {}
};
派生类中:
class Derived : public Base {
public:
void func() const override { /* ... */ } // 正确:签名匹配
void func(int x) override { /* ... */ } // 错误:参数不同,编译器报错
};
总结
在你的自定义异常类MyException
中,override
确保what()
函数正确重写了exception
类的虚函数,避免因签名不匹配导致的潜在错误。
0 条评论
目前还没有评论...