60 likes | 233 Views
C++ Functions, Classes, and Templates. C++ functions encapsulate behavior Data used/modified by a function must be passed in via parameters Data produced by a function must be passed out via return type Classes (and structs) encapsulate related data and behavior
E N D
C++ Functions, Classes, and Templates • C++ functions encapsulate behavior • Data used/modified by a function must be passed in via parameters • Data produced by a function must be passed out via return type • Classes (and structs) encapsulate related data and behavior • Member variables maintain each object’s state • Member functions (methods) and operators have direct access to member variables • Templates are used to make classes/structs/functions generic • For example, vector class template can hold different data types • For example, sort algorithm works with different containers as well
Declaring, Defining, Calling C++ Functions // function declarations in myfile.h void foo (); void baz (int j); // function definitions in myfile.cpp void baz (int j){ cout << j << endl; // prints passed value } void foo (){ int i = 7; // foo calls baz, passing variable i to it baz (i); }
Declaring, Defining, Using C++ Structs/Classes // declaration (in Point2d.h) struct Point2D { Point2D (int x, int y); bool operator< (const Point2D &) const; int x_; int y_; }; // definitions (in Point2d.cpp) Point2D::Point2D (int x, int y) : x_(x), y_(y) {} bool Point2D::operator< (const Point2D & p2d) const { return (x_ < p2d.x_) || ((x_ == p2d.x_) && (y_ < p2d.y_)); } promises not to modify object on which it’s called base class/struct and member initialization list scoping operator
Using C++ Struct/Class Templates (with Structs) // using standard library code #include <vector> using namespace std; // using user-defined code #include “point2d.h” // main function definition int main (int, char *[]) { vector<Point2D> v; // must give a type here v.push_back(Point2D(2,3)); v.push_back(Point2D(1,4)); return 0; }
Using C++ Function Templates (STL Algorithms) // same as before, and add algorithm library #include <vector> #include <algorithm> using namespace std; #include “point2d.h” int main (int, char *[]) { vector<Point2D> v; v.push_back(Point2D(2,3)); v.push_back(Point2D(1,4)); // reorders the points in the vector // note that you don’t give a type here! sort (v.begin(), v.end()); return 0; }
Another Useful STL Algorithm #include <string> #include <iostream> #include <algorithm> using namespace std; int main (int argc, char * argv[]) { if (argc != 2) { cout << “usage: ” << argv[0] << “ <string>” << endl; return -1; } string s(argv[1]), t(argv[1]); do { next_permutation(s.begin(), s.end()); cout << s << endl; } while (s != t); return 0; }