IDE/Compilation
IDE
In AptanaStudio3, add the following repository to support C/C++:
http://download.eclipse.org/tools/cdt/releases/helios
Compilation
Example (both below sources are identical):
Source1.cpp
|
Source2.cpp
|
#include <iostream>
int main()
{
std::cout << "Hello world" << std::endl;
return 0;
}
|
#include <iostream>
using namespace std;
int main()
{
cout << "Hello world" << endl;
return 0;
}
|
Let's compile:
g++ -Wall -o main source1.cpp
And run:
$ ./main
Hello world
Note
If you have several *.cpp source files, all you need to do is to list them in the command, as follows: g++ -Wall -o main source1.cpp source2.cpp source3.cpp
Variables & references
Source
|
Output
|
#include <iostream>
#include <string>
using namespace std;
int main()
{
int age(37);
string name("Alice Shaw");
double const pi(3.14159); // Constant. You can't modify it.
cout << "Hello " << name << ". You are " << age << " years old." << endl;
return 0;
}
|
Hello Alice Shaw. You are 37 years old.
|
In C++, you can define references as follows:
Source
|
Output
|
#include <iostream>
#include <string>
using namespace std;
int main()
{
int num(16);
int& refnum1(num);
int& refnum2(num);
string name("Alice Shaw");
string &refname(name);
cout << "Num: " << num << endl;
cout << "Ref Num 1: " << refnum1 << endl;
cout << "Ref Num 2: " << refnum2 << endl;
cout << "Name: " << name << endl;
cout << "Ref name: " << refname << endl;
return 0;
}
|
$ ./main
Num: 16
Ref Num 1: 16
Ref Num 2: 16
Name: Alice Shaw
Ref name: Alice Shaw
|
Below is a more concrete example:
Source
|
Run
|
#include <iostream>
using namespace std;
void swap(int &a, int &b)
{
int temp(a);
a = b;
b = temp;
}
int main() {
int a(2), b(4);
cout << "a=" << a << ", b=" << b << endl;
swap(a, b);
cout << "a=" << a << ", b=" << b << endl;
return 0;
}
|
$ ./main
a=2, b=4
a=4, b=2
|
Arrays
Static size
Static size arrays work the same way as for C:
Source
|
Run
|
#include <iostream>
using namespace std;
double avg(double scores[], int len);
int main() {
int const len(5);
double scores[len];
scores[0] = 13.2;
scores[1] = 10.5;
scores[2] = 15;
scores[3] = 17.5;
scores[4] = 12.8;
cout << "Average: " << avg(scores, len) << endl;
return 0;
}
double avg(double scores[], int len)
{
double avg(0);
int i(0);
for(i=0; i<len; i++)
avg += scores[i];
avg /= len;
return avg;
}
|
$ ./main
Average: 13.8
|
Dynamic size
To use a dynamic size array, first include the vector header:
Then do as follows:
// Array of integers, size of 5, filled with 3
vector<int> tab(5, 3);
// Array of strings, size of 5, filled with "hello"
vector<string> tab(5, "hello");
// Array of double, with no size specified and no default value
vector<double> tab;
To add and delete cells, respectively use array_name.push_back(val) and array_name.pop_back() as follows:
Source
|
Output
|
main.h
|
#ifndef DEF_MAIN
#define DEF_MAIN
#include <vector>
void tabinfo(std::vector<double> const &tab);
#endif
|
main.cpp
|
#include <iostream>
#include <vector>
#include "main.h"
using namespace std;
int main() {
vector<double> scores(5,0);
int i(0);
scores[0] = 13.2;
scores[1] = 10.5;
scores[2] = 15;
scores[3] = 17.5;
scores[4] = 12.8;
tabinfo(scores);
scores.push_back(12.3);
tabinfo(scores);
for(i=0; i<4; i++) {
scores.pop_back();
tabinfo(scores);
}
return 0;
}
void tabinfo(vector<double> const &tab)
{
int i(0);
cout << "Size: " << tab.size() << ", Items:";
for (i=0; i<tab.size(); i++)
cout << " " << tab[i];
cout << endl;
}
|
|
Size: 5, Items: 13.2 10.5 15 17.5 12.8
Size: 6, Items: 13.2 10.5 15 17.5 12.8 12.3
Size: 5, Items: 13.2 10.5 15 17.5 12.8
Size: 4, Items: 13.2 10.5 15 17.5
Size: 3, Items: 13.2 10.5 15
Size: 2, Items: 13.2 10.5
|
Multi-dimensional arrays
Source
|
Output
|
main.h
|
#ifndef DEF_MAIN
#define DEF_MAIN
#include <vector>
void showtab(std::vector<std::vector<int>> const &tab);
#endif
|
main.cpp
|
#include <iostream>
#include <vector>
#include "main.h"
using namespace std;
int main() {
vector<vector<int>> tab;
// 1st row of size 5 filled with 1
tab.push_back(vector<int>(5,1));
// 2nd row of size 5 filled with 2
tab.push_back(vector<int>(5,2));
tab[0][3] = 8;
tab[0][4] = 9;
tab[1][1] = 5;
tab[1][2] = 4;
showtab(tab);
// Add 3 at the end of the 1st row
tab[0].push_back(3);
showtab(tab);
return 0;
}
void showtab(vector<vector<int>> const &tab)
{
unsigned int row(0), col(0);
for(row=0; row<tab.size(); row++) {
for(col=0; col<tab[0].size(); col++) {
cout << " | " << tab[row][col];
}
cout << " |" << endl;
}
cout << "--------------------------" << endl;
}
|
|
| 1 | 1 | 1 | 8 | 9 |
| 2 | 5 | 4 | 2 | 2 |
--------------------------
| 1 | 1 | 1 | 8 | 9 | 3 |
| 2 | 5 | 4 | 2 | 2 | 0 |
--------------------------
|
Heterogeneous containers
main.cpp
|
#include <iostream>
#include <string>
#include <vector>
#include "Garage.h"
using namespace std;
void showInfo(Vehicle const &vehicle);
int main()
{
vector<Vehicle*> vehicles;
unsigned int i(0);
vehicles.push_back(new Car(8550, 5));
vehicles.push_back(new Car(3950, 3));
vehicles.push_back(new Motorcycle(3250, 200.5));
vehicles[0]->showInfo();
vehicles[2]->showInfo();
for(i=0; i<vehicles.size(); ++i)
{
delete vehicles[i];
vehicles[i] = 0;
}
return 0;
}
void showInfo(Vehicle const &vehicle)
{
vehicle.showInfo();
}
|
|
Garage.h
|
#ifndef DEF_GARAGE
#define DEF_GARAGE
class Vehicle
{
public:
Vehicle(int price);
virtual void showInfo() const;
virtual ~Vehicle();
protected:
int m_price;
};
class Car: public Vehicle
{
public:
Car(int price, int doors);
virtual void showInfo() const;
virtual ~Car();
private:
int m_doors;
};
class Motorcycle : public Vehicle
{
public:
Motorcycle(int price, double speed);
virtual void showInfo() const;
virtual ~Motorcycle();
private:
double m_speed;
};
#endif /* DEF_GARAGE */
|
|
Garage.cpp
|
#include <iostream>
#include <string>
#include "Garage.h"
using namespace std;
/***
* Vehicle
*/
Vehicle::Vehicle(int price) : m_price(price) {}
Vehicle::~Vehicle() {}
void Vehicle::showInfo() const {
cout << "This vehicle costs $" << m_price << "." << endl;
}
/***
* Car
*/
Car::Car(int price, int doors) : Vehicle(price), m_doors(doors) {}
Car::~Car() {}
void Car::showInfo() const {
cout << "This car has " << m_doors << " doors and costs $" << m_price << "." << endl;
}
/***
* Motorcycle
*/
Motorcycle::Motorcycle(int price, double speed) : Vehicle(price), m_speed(speed) {}
Motorcycle::~Motorcycle() {}
void Motorcycle::showInfo() const {
cout << "This motorcycle can drive " << m_speed << "mph and costs $" << m_price << "." << endl;
}
|
|
The above code produces the following output:
This car has 5 doors and costs $8550.
This motorcycle can drive 200.5mph and costs $3250.
Files
Write and Read file
Source
|
Output
|
#include <iostream>
#include <fstream> /* ifstream(), ofstream() */
#include <string> /* getline() */
using namespace std;
int main()
{
string const myfile("test.txt");
// file stream (write)
ofstream mystream(myfile.c_str());
if(!mystream) perror("Error creating stream");
// Write to file
mystream << "This is a test file" << endl;
mystream << "Hello world!" << endl;
// file stream (read)
ifstream readfile(myfile.c_str());
if(!readfile) perror("Error creating stream");
// Read a word
string word;
readfile >> word;
cout << "A word: " << word << endl;
// Read file line by line
string line;
while( getline(readfile, line) )
cout << "A line: " << line << endl;
return 0;
}
|
$ ./main
A word: This
A line: is a test file
A line: Hello world!
|
Pointers
Syntax
|
Description
|
Example
|
&thing
|
Address of thing
|
Source
|
Output
|
#include <iostream>
using namespace std;
int main()
{
int num(3);
cout << "Address of num: " << &num << endl;
return 0;
}
|
Address of num: 0x7ffee04a04ec
|
|
type *ptr
|
a pointer of type named ptr
Examples:
string *pVar1(nullptr);
unsigned int *pVar2(nullptr);
vector<int> *pVar3(nullptr);
|
Syntax
|
Output
|
#include <iostream>
using namespace std;
int main()
{
int num(10);
int *pNum(nullptr);
pNum = #
cout << "num=" << num << endl;
cout << "&num=" << &num << endl;
cout << "pNum=" << pNum << endl;
cout << "*pNum=" << *pNum << endl;
return 0;
}
|
num=10
&num=0x7ffe377fd054
pNum=0x7ffe377fd054
*pNum=10
|
|
*ptr
|
the value of whatever ptr is pointed at
|
Pointers and references
Source
|
Run
|
#include <iostream>
using namespace std;
int main()
{
int num1(3); // num1 set to 3
int &num2(num1); // num2 as reference to num1
cout << "num1=" << num1 << ", num2=" << num2 << endl;
// If num1 is updated, num2 is also set to the updated value
num1 = 4;
cout << "num1=" << num1 << ", num2=" << num2 << endl;
// If num2 is updated, num1 is also updated
num2 = 5;
cout << "num1=" << num1 << ", num2=" << num2 << endl;
// This is because both num1 and num2 point to the same address
cout << "Addr num1=" << &num1 << ", Addr. num2=" << &num2 << endl;
return 0;
}
|
num1=3, num2=3
num1=4, num2=4
num1=5, num2=5
Addr num1=0x7ffcc98af0f4, Addr. num2=0x7ffcc98af0f4
|
Memory allocation
C
|
C++
|
int *ageAlice = NULL;
ageAlice = malloc(sizeof(int));
if(ageAlice==NULL) exit(1);
// ...
free(ageAlice);
|
int *ageAlice(0);
ageAlice = new int;
// ...
delete(ageAlice);
ageAlice = 0;
|
Below is a full example:
Source
|
Run
|
#include <iostream>
using namespace std;
int main()
{
int agePaul(0);
int *ageAlice(0);
ageAlice = new int;
cout << "How old is Paul? ";
cin >> agePaul;
cout << "How old is Alice? ";
cin >> *ageAlice;
cout << "Paul is " << agePaul << " years old and Alice is " << *ageAlice << " years old." << endl;
delete(ageAlice);
ageAlice = 0;
return 0;
}
|
$ ./main
How old is Paul? 33
How old is Alice? 35
Paul is 33 years old and Alice is 35 years old.
|
Classes
Classes
The following program:
main.cpp
|
#include <iostream>
#include <string>
#include "Player.h"
using namespace std;
int main()
{
// Instantiation of Player class
Player player1, player2("Sword", 20);
// Actions (methods called from Player class)
player2.attack(player1);
player1.drinkHealingPotion(20);
player2.attack(player1);
player1.attack(player2);
player2.switchWeapon("Ax", 40);
player2.attack(player1);
cout << "=== Player 1 ===" << endl;
player1.showStatus();
cout << "=== Player 2 ===" << endl;
player2.showStatus();
return 0;
}
|
|
Player.h
|
#ifndef DEF_PLAYER
#define DEF_PLAYER
#include <iostream>
#include <string>
#include "Weapon.h"
class Player
{
// Methods are public so that we can call them from main()
public:
Player(); // Default constructor
Player(std::string weaponName, int weaponDamage); // Constructor that overrides the default weapon
~Player(); // Destructor
void sufferDamage(int damage);
void attack(Player &target);
void drinkHealingPotion(int potionQuantity);
void switchWeapon(std::string newWeaponName, int newWeaponDamage);
bool isAlive();
void showStatus();
// Attributes should always remain private
private:
int m_lives;
int m_mana;
Weapon m_weapon;
};
#endif
|
Player.cpp
|
#include "Player.h"
using namespace std;
// Initialization
Player::Player() : m_lives(100), m_mana(100) {}
Player::Player(string weaponName, int weaponDamage) : m_lives(100), m_mana(100), m_weapon(weaponName, weaponDamage) {}
// Destructor
Player::~Player() {}
void Player::sufferDamage(int damage)
{
m_lives -= damage;
if (m_lives < 0) m_lives = 0;
}
void Player::attack(Player &target)
{
target.sufferDamage(m_weapon.getDamage());
}
void Player::drinkHealingPotion(int potionQuantity)
{
m_lives += potionQuantity;
if(m_lives>100) m_lives = 100;
}
void Player::switchWeapon(string newWeaponName, int newWeaponDamage)
{
m_weapon.switchWeapon(newWeaponName, newWeaponDamage);
}
bool Player::isAlive()
{
if (m_lives > 0)
return true;
else
return false;
}
void Player::showStatus()
{
cout << "Lives: " << m_lives << endl;
cout << "Mana: " << m_mana << endl;
m_weapon.showWeapon();
}
|
|
Weapon.h
|
#ifndef DEF_WEAPON
#define DEF_WEAPON
#include <iostream>
#include <string>
class Weapon
{
public:
Weapon();
Weapon(std::string name, int damage);
~Weapon();
void switchWeapon(std::string name, int damage);
void showWeapon();
int getDamage() const; // accessor
private:
std::string m_name;
int m_damage;
};
#endif
|
Weapon.cpp
|
#include "Weapon.h"
using namespace std;
// Init
Weapon::Weapon() : m_name("Knife"), m_damage(10) {}
Weapon::Weapon(string name, int damage) : m_name(name), m_damage(damage) {}
// Destructor
Weapon::~Weapon() {}
void Weapon::switchWeapon(string name, int damage)
{
m_name = name;
m_damage = damage;
}
void Weapon::showWeapon()
{
cout << "Weapon: " << m_name << " (Damage: " << m_damage << ")" << endl;
}
int Weapon::getDamage() const
{
return m_damage;
}
|
|
...will show the following output:
=== Player 1 ===
Lives: 40
Mana: 100
Weapon: Knife (Damage: 10)
=== Player 2 ===
Lives: 90
Mana: 100
Weapon: Ax (Damage: 40)
Inheritance
main.cpp
|
#include <iostream>
#include <string>
#include "Vehicle.h"
#include "Car.h"
#include "Motorcycle.h"
using namespace std;
int main()
{
Vehicle v(6800);
v.showInfo();
cout << "-----" << endl;
Car c(8500, 4);
c.showInfo();
cout << "-----" << endl;
Motorcycle m(3850, 200);
m.showInfo();
return 0;
}
|
|
Vehicle.h
|
#ifndef VEHICLE_H_
#define VEHICLE_H_
class Vehicle {
public:
Vehicle(int price);
virtual ~Vehicle();
void showInfo() const;
/* protected indicates that it
remains private but accessible
from the children */
protected:
int m_price;
};
#endif /* VEHICLE_H_ */
|
Vehicle.cpp
|
#include <iostream>
#include <string>
#include "Vehicle.h"
using namespace std;
Vehicle::Vehicle(int price)
: m_price(price) {}
Vehicle::~Vehicle() {}
void Vehicle::showInfo() const
{
cout << "This vehicle costs $"
<< m_price
<< " (call from Vehicle class)."
<< endl;
}
|
|
Car.h
|
#ifndef CAR_H_
#define CAR_H_
class Car : public Vehicle {
public:
Car(int price, int doors);
virtual ~Car();
void showInfo() const;
private:
int m_doors;
};
#endif /* CAR_H_ */
|
Car.cpp
|
#include <iostream>
#include <string>
#include "Vehicle.h"
#include "Car.h"
using namespace std;
Car::Car(int price, int doors)
: Vehicle(price), m_doors(doors) {}
Car::~Car() {}
void Car::showInfo() const
{
/* Access price thanks to the
protected mode in Vehicle class */
cout << "This vehicle costs $"
<< m_price
<< " (access m_price from Vehicle)."
<< endl;
cout << "This car has "
<< m_doors
<< " doors (Car member)."
<< endl;
}
|
|
Motorcycle.h
|
#ifndef MOTORCYCLE_H_
#define MOTORCYLE_H_
class Motorcycle : public Vehicle {
public:
Motorcycle(int price, int speed);
virtual ~Motorcycle();
void showInfo() const;
private:
int m_speed;
};
#endif /* MOTORCYLE_H_ */
|
Motorcycle.cpp
|
#include <iostream>
#include <string>
#include "Vehicle.h"
#include "Motorcycle.h"
using namespace std;
Motorcycle::Motorcycle(int price, int speed)
: Vehicle(price), m_speed(speed) {}
Motorcycle::~Motorcycle() {}
void Motorcycle::showInfo() const
{
// Call showInfo method from Vehicle
Vehicle::showInfo();
cout << "This motorcycle drives "
<< m_speed
<< "mph (Motorcycle member)."
<< endl;
}
|
|
The above code produces the following output:
This vehicle costs $6800 (call from Vehicle class).
-----
This vehicle costs $8500 (access m_price from Vehicle).
This car has 4 doors (Car member).
-----
This vehicle costs $3850 (call from Vehicle class).
This motorcycle drives 200mph (Motorcycle member).
Static methods
main.cpp
|
#include <iostream>
#include "Hello.h"
using namespace std;
int main()
{
Hello::sayHello();
return 0;
}
|
|
Hello.h
|
#ifndef DEF_HELLO
#define DEF_HELLO
class Hello
{
public:
Hello();
virtual ~Hello();
static void sayHello();
};
#endif
|
|
Hello.cpp
|
#include <iostream>
#include "Hello.h"
using namespace std;
Hello::Hello() {}
Hello::~Hello() {}
void Hello::sayHello()
{
cout << "Hello" << endl;
}
|
|
The above code will produce the following output:
Hello
Operator overloading
Comparison operators ("==" and "!=")
Below is the code for the == and != operators. The same logic can be applied for <, <=, > and >=.
main.cpp
|
#include <iostream>
#include <string>
#include "Person.h"
using namespace std;
int main()
{
Person person1("alice", 38), person2("paul", 35),
person3("alice", 34), person4("paul", 35);
cout << "Person1: ";
person1.showInfo();
cout << "Person2: ";
person2.showInfo();
cout << "Person3: ";
person3.showInfo();
cout << "Person4: ";
person4.showInfo();
if (person1 == person3)
cout << "Person 1 and 3 are the same" << endl;
if (person1 != person3)
cout << "Person 1 and 3 are different" << endl;
if (person2 == person4)
cout << "Person 2 and 4 are the same" << endl;
if (person2 != person4)
cout << "Person 2 and 4 are different" << endl;
return 0;
}
|
|
Person.h
|
#ifndef DEF_PERSON
#define DEF_PERSON
class Person
{
public:
Person(std::string name, int age);
~Person();
void showInfo();
bool isIdentical(Person const& person) const;
private:
std::string m_name;
int m_age;
};
bool operator==(Person const& person1, Person const& person2);
bool operator!=(Person const& person1, Person const& person2);
#endif
|
|
Person.cpp
|
#include <iostream>
#include <string>
#include "Person.h"
using namespace std;
Person::Person(string name, int age)
: m_name(name), m_age(age) {}
Person::~Person() {}
void Person::showInfo()
{
cout << m_name << " is " << m_age << " years old." << endl;
}
bool Person::isIdentical(Person const& person) const
{
return (m_name == person.m_name && m_age == person.m_age);
}
bool operator==(Person const& person1, Person const& person2)
{
return person1.isIdentical(person2);
}
bool operator!=(Person const& person1, Person const& person2)
{
return !person1.isIdentical(person2);
}
|
|
The above code will show the following output:
Person1: alice is 38 years old.
Person2: paul is 35 years old.
Person3: alice is 34 years old.
Person4: paul is 35 years old.
Person 1 and 3 are different
Person 2 and 4 are the same
Arithmetic operators ("+", "-", "+=" and "-=")
main.cpp
|
#include <iostream>
#include <string>
#include "Duration.h"
using namespace std;
int main()
{
Duration duration1(3,25,25),
duration2(1,45,38),
duration3;
cout << "Duration 1: ";
duration1.showDuration();
cout << "Duration 2: ";
duration2.showDuration();
duration3 = duration1 + duration2;
cout << "Duration (1)+(2): ";
duration3.showDuration();
duration3 = duration1 - duration2;
cout << "Duration (1)-(2): ";
duration3.showDuration();
return 0;
}
|
|
Duration.h
|
#ifndef DEF_DURATION
#define DEF_DURATION
class Duration {
public:
Duration(int hours=0, int minutes=0, int seconds=0);
~Duration();
void showDuration();
Duration& operator+=(const Duration &duration);
Duration& operator-=(const Duration &duration);
private:
int m_hours;
int m_minutes;
int m_seconds;
};
Duration operator+(Duration const& duration1, Duration const& duration2);
Duration operator-(Duration const& duration1, Duration const& duration2);
#endif /* DEF_DURATION */
|
|
Duration.cpp
|
#include <iostream>
#include <string>
#include <iomanip> /* for proper time format */
#include "Duration.h"
using namespace std;
Duration::Duration(int hours, int minutes, int seconds)
: m_hours(hours), m_minutes(minutes), m_seconds(seconds) {}
Duration::~Duration() {}
void Duration::showDuration()
{
cout << setfill('0') << setw(2) << m_hours
<< ":" << setfill('0') << setw(2) << m_minutes
<< ":" << setfill('0') << setw(2) << m_seconds
<< endl;
}
Duration& Duration::operator+=(const Duration &duration)
{
int nseconds = m_hours * 3600 + m_minutes * 60 + m_seconds;
nseconds += duration.m_hours * 3600 + duration.m_minutes * 60 + duration.m_seconds;
m_hours = nseconds / 3600;
m_minutes = nseconds % 3600 / 60;
m_seconds = nseconds % 3600 % 60;
return *this;
}
Duration& Duration::operator-=(const Duration &duration)
{
int nseconds = m_hours * 3600 + m_minutes * 60 + m_seconds;
nseconds -= duration.m_hours * 3600 + duration.m_minutes * 60 + duration.m_seconds;
m_hours = nseconds / 3600;
m_minutes = nseconds % 3600 / 60;
m_seconds = nseconds % 3600 % 60;
return *this;
}
Duration operator+(Duration const& duration1, Duration const& duration2)
{
Duration copyDuration1(duration1);
copyDuration1 += duration2;
return copyDuration1;
}
Duration operator-(Duration const& duration1, Duration const& duration2)
{
Duration copyDuration1(duration1);
copyDuration1 -= duration2;
return copyDuration1;
}
|
|
It outputs:
Duration 1: 03:25:25
Duration 2: 01:45:38
Duration (1)+(2): 05:11:03
Duration (1)-(2): 01:39:47
Stream operator
Modify Duration.h and Duration.cpp as follows:
Duration.h
|
#ifndef DEF_DURATION
#define DEF_DURATION
class Duration {
public:
Duration(int hours=0, int minutes=0, int seconds=0);
~Duration();
void showDuration(std::ostream &mystream) const;
Duration& operator+=(const Duration &duration);
Duration& operator-=(const Duration &duration);
private:
int m_hours;
int m_minutes;
int m_seconds;
};
Duration operator+(Duration const& duration1, Duration const& duration2);
Duration operator-(Duration const& duration1, Duration const& duration2);
std::ostream &operator<<(std::ostream &mystream, Duration const& duration);
#endif /* DEF_DURATION */
|
|
Duration.cpp
|
#include <iostream>
#include <string>
#include <iomanip> /* for proper time format */
#include "Duration.h"
using namespace std;
Duration::Duration(int hours, int minutes, int seconds)
: m_hours(hours), m_minutes(minutes), m_seconds(seconds) {}
Duration::~Duration() {}
void Duration::showDuration(ostream &mystream) const
{
mystream << setfill('0') << setw(2) << m_hours
<< ":" << setfill('0') << setw(2) << m_minutes
<< ":" << setfill('0') << setw(2) << m_seconds;
}
Duration& Duration::operator+=(const Duration &duration)
{
int nseconds = m_hours * 3600 + m_minutes * 60 + m_seconds;
nseconds += duration.m_hours * 3600 + duration.m_minutes * 60 + duration.m_seconds;
m_hours = nseconds / 3600;
m_minutes = nseconds % 3600 / 60;
m_seconds = nseconds % 3600 % 60;
return *this;
}
Duration& Duration::operator-=(const Duration &duration)
{
int nseconds = m_hours * 3600 + m_minutes * 60 + m_seconds;
nseconds -= duration.m_hours * 3600 + duration.m_minutes * 60 + duration.m_seconds;
m_hours = nseconds / 3600;
m_minutes = nseconds % 3600 / 60;
m_seconds = nseconds % 3600 % 60;
return *this;
}
Duration operator+(Duration const& duration1, Duration const& duration2)
{
Duration copyDuration1(duration1);
copyDuration1 += duration2;
return copyDuration1;
}
Duration operator-(Duration const& duration1, Duration const& duration2)
{
Duration copyDuration1(duration1);
copyDuration1 -= duration2;
return copyDuration1;
}
ostream &operator<<(ostream &mystream, Duration const& duration)
{
duration.showDuration(mystream);
return mystream;
}
|
|
Now, we can display our class directly from cout:
main.cpp
|
#include <iostream>
#include <string>
#include "Duration.h"
using namespace std;
int main()
{
Duration duration1(3,25,25),
duration2(1,45,38);
cout << "Duration 1: " << duration1 << endl;
cout << "Duration 2: " << duration2 << endl;
cout << "Duration (1)+(2): " << duration1+duration2 << endl;
cout << "Duration (1)-(2): " << duration1-duration2 << endl;
return 0;
}
|
Some programs
- guess-word
- Player 1 is entering a secret. This secret is scrambled and shown to player 2 who should guess the secret
- Download
Subcategories
This category has the following 2 subcategories, out of 2 total.