ece150: add exceptions and classes 2
This commit is contained in:
parent
45f135f955
commit
d7054beee3
@ -488,3 +488,72 @@ Namespaces can also be nested within namespaces.
|
|||||||
`std::cout` does weird shenanigans that passes itself to every function afterward, such as `std::endl`.
|
`std::cout` does weird shenanigans that passes itself to every function afterward, such as `std::endl`.
|
||||||
|
|
||||||
This means that `std::cout << std::endl;` is equivalent to `std::endl(std::cout);`.
|
This means that `std::cout << std::endl;` is equivalent to `std::endl(std::cout);`.
|
||||||
|
|
||||||
|
### Operator overloading
|
||||||
|
|
||||||
|
Operators can be overloaded for various classes.
|
||||||
|
|
||||||
|
!!! example
|
||||||
|
Overloading for displaying to `cout`:
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
std::ostream operator<<(std::ostream &out, ClassName const &p) {
|
||||||
|
out << "text here";
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
### Constructors
|
||||||
|
|
||||||
|
Constructors can be defined with default values after a colon and before the function body:
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
Rational::Rational():
|
||||||
|
numer_{0},
|
||||||
|
denom_{0} {
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Subsequent members can even use the values of previous ones.
|
||||||
|
|
||||||
|
Constructors can also contain parameters with default values, but default values must also be present in the class declaration.
|
||||||
|
|
||||||
|
### Member functions
|
||||||
|
|
||||||
|
A `const` after a member function forbids the modification of any member variables within that function.
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
int get_val() const {
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Exceptions
|
||||||
|
|
||||||
|
`#define NDEBUG` turns off assertions.
|
||||||
|
|
||||||
|
`static_cast<double>(var)` performs the typical implicit conversion explicitly during compile time.
|
||||||
|
|
||||||
|
Exceptions are expensive error handlers that **do not protect** from program termination (e.g., attempt to access invalid memory).
|
||||||
|
|
||||||
|
The following are all exception classes in `std`:
|
||||||
|
|
||||||
|
- `domain_error`
|
||||||
|
- `runtime_error`
|
||||||
|
- `range_error`
|
||||||
|
- `overflow_error`
|
||||||
|
- `underflow_error`
|
||||||
|
- `logic_error`
|
||||||
|
- `length_error`
|
||||||
|
- `out_of_range`
|
||||||
|
|
||||||
|
`...` is a catch-all exception.
|
||||||
|
|
||||||
|
!!! example
|
||||||
|
```cpp
|
||||||
|
try {
|
||||||
|
throw std::domain_error{"cannot compute stupidity"};
|
||||||
|
} catch (std::domain_error &e) {
|
||||||
|
std::cerr << e->what();
|
||||||
|
} catch (...) {
|
||||||
|
}
|
||||||
|
```
|
||||||
|
Loading…
Reference in New Issue
Block a user