1. cin and strings
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string mystr;
cout << "What's your name? ";
getline (cin, mystr);
cout << "Hello " << mystr << ".\n";
return 0;
}
2. stringstream
string mystr ("1204");
int myint;
stringstream(mystr) >> myint;
3. passed by reference
#include <iostream>
using namespace std;
void duplicate (int& a, int& b, int& c)
{
a*=2;
b*=2;
c*=2;
}
int main ()
{
int x=1, y=3, z=7;
duplicate (x, y, z);
cout << "x=" << x << ", y=" << y << ", z=" << z;
return 0;
}
By qualifying them as const, the function is forbidden to modify the values of neither a nor b, but can actually
access their values as references:
string concatenate (const string& a, const string& b)
{
return a+b;
}
4. function template (are_equal(10,10.0) Is equivalent to: are_equal<int,double>(10,10.0))
#include <iostream>
using namespace std;
template <class T, class U>
bool are_equal (T a, U b)
{
return (a==b);
}
int main ()
{
if (are_equal(10,10.0))
cout << "x and y are equal\n";
else
cout << "x and y are not equal\n";
return 0;
}
5. pointer
#include <iostream>
using namespace std;
int main ()
{
int firstvalue, secondvalue;
int * mypointer;
mypointer = &firstvalue;
*mypointer = 10;
mypointer = &secondvalue;
*mypointer = 20;
cout << "firstvalue is " << firstvalue << '\n';
cout << "secondvalue is " << secondvalue << '\n';
return 0;
}
The arrow operator (->) is a dereference operator that is used exclusively with pointers to objects that have members.
movies_t * pmovie;
pmovie->title is, for all purposes, equivalent to: (*pmovie).title
6.
Classes are an expanded concept of data structures: like data structures, they can contain data members,
but they can also contain functions as members.
empty parentheses cannot be used to call the default constructor:
Rectangle rectb; // ok, default constructor called
Rectangle rectc(); // oops, default constructor NOT called
No comments:
Post a Comment