Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Cs162 exam notes
- Good Practices
- If a function is not changing anything, declare it const
- Make getters and setters for EVERY class and USE them - this future proofs your code
- Have a copy class for your classes to assign one object to another
- Pass by reference whenever passing data structures
- When you overload the << operator it cannot be a member function of the class (declare friend if it needs to access private info)
- Only make something a friend of a class IF it needs to directly access private stuff
- Pointer: int*
- Dereference: *x
- vector<int*> x{};
- v.push_back(new int{23});
- cout << *v[0] << endl;
- v[0]->method(thing);
- When you dynamically allocate memory you get back a pointer
- Common includes/include guard
- #ifndef INTEGERSET_H //include guard
- #define INTEGERSET_H
- #include <vector>//vector
- #include <iostream> //cout
- #include <stdexcept> //exceptions
- #include <sstream> //ostream and ostringstream (use .str() on ostringstreams)
- #endif // INTEGERSET_H //end include guard
- Basic Class outline
- .h file:
- #ifndef WEAPON_H
- #define WEAPON_H
- class Weapon {
- public:
- Weapon(const int);
- void setDamage(const int) const;
- int getDamage() const;
- private:
- int damage;
- };
- #endif // WEAPON_H
- .cpp file:
- #include "Weapon.h"
- Weapon::Weapon(const int in) {
- }
- void Weapon::setDamage(const int in) const {
- }
- int Weapon::getDamage() const {
- }
- Operator Overloading
- object operator+(object input) {
- object result{};
- result.thing = this->thing + input.thing;
- return result;
- }
- std::ostream& operator<<(std::ostream& oin,Rational in) { //overloads left shift operator
- oin << in.toString();
- return oin;
- }
- // Define prefix increment operator.
- Point& Point::operator++()
- {
- _x++;
- _y++;
- return *this;
- }
- // Define postfix increment operator.
- Point Point::operator++(int)
- {
- Point temp = *this;
- ++*this;
- return temp;
- }
- Looping structures
- for (int i = 0; i < target; i++) {
- }
- do {
- stuff;
- } while (condition);
- while(condition) {
- statement(s);
- }
- Dynamic memory allocation:
- Array<int*,10> XXX{nullptr}; //when we use new it always gives us a pointer to an object
- XXX[0] = new int{234}; //allocates memory for a new int in this array
- Delete XXX[0]; //deletes element of array, array still exists
- XXX[0] = nullptr; //wipes memory where that element was
- Errors:
- #include <stdexcept>
- throw std::invalid_argument(“invalid input”);
- try{
- Clock x{43201};
- }
- catch (invalid_argument& e) {
- cout << "An exception occurred I think, here's what it might say:" << e.what() << endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement