Vous êtes sur la page 1sur 2

/*

* File: 20160909_CPP_L01.cpp.
* Title: 2016-09-09 C++ Lesson 01
* Author: Renato Montes
* Description: Notes for Albert Wei's C++ class
*/

//multi-paradigm: procedural, OO, generic programming


//C++11 will be taught

/* First program */
#include <iostream>

int main() {
std::cout << "hello world" << std::endl;
}

//:: is the scope operator


//<< is the insertion operator (a.k.a. output operator)

//cout is an ostream object associated with standard output.


// there's a class called ostream. the system has already created
// several objects for us

//cerr is an ostream object associated with standard error


//clog is another ostream object

//Note that ostream is actually a specialization of basic_ostream for char:


typedef basic_ostream<char> ostream;

//C++ has operator overloading


std::cout << "hello"; // full name of "<<": operator<<

/*Second Program*/
#include <iostream>

struct Hello {
Hello() { std::cout << "hello world" << std::endl; } //print at constructor
// use "ctor" as abbreviation for constructor
~Hello() { std::cout << "goodbye world" << std::endl; } //destructor
// use "dtor" for destructor
};

int main() {
Hello h; // cf. int n;
// Hello is type, h is the name of the variable
}

//in order to not write std:: use a "using declaration":


using std::cout;
//convenient if using cout about 10 or so times (at least)
//in order to "import" everything in std, use a "using directive":
using namespace std;

//don't put using declarations and using directives in a header file


//boolean type: bool 2 values: true/false

//references, which are basically an alias

void swap(int& a, int& b) {


int tmp = a;
a = b;
b = tmp;
}

int m = 1, n = 2;
swap(m, n);
//a is a reference to m, b is a reference to n

//let's write a generic swap:


template<typename T>
void swap(T& a, T& b) {
T tmp = a;
a = b;
b = tmp;
}
//this is called a function template. we can also have "class templates"
//basic_ostream is a class, and ostream is a template because you can pass
// different types

//calling it:
double d1 = 3.14, d2 = 2.71;
swap(d1,d2);
long l1 = 1234, l2=5678;
swap(l1,l2);
swap(l1,d1);//doesn't compile
swap<double>(l1,d1);//also won't work, but would temporarily convert l1
// to a double

/* Class Templates */
//e.g. vector<>, which is dynamic (it can grow at the end)
//when using vector<>, must specify the type: vector<int>
vector<int> v;
v.push_back(3);
v.push_back(1);

//you can a vector<> of anything


vector<vector<int>> vv;
vv.push_back(v);//note vv gets a COPY of v!!!
//this is the same for all containers in the std library, they get a copy
//there's a way around it using pointers, by giving the container a copy of
// the pointer

Vous aimerez peut-être aussi