An example of compound type is the
string
class. Variables of this type are able to store sequences of characters, such as words or sentences. A very useful feature!A first difference with fundamental data types is that in order to declare and use objects (variables) of this type, the program needs to include the header where the type is defined within the standard library (header
<string>
):// my first string
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string mystring;
mystring = "This is a string";
cout << mystring;
return 0;
}
printout:
This is a string
As you can see in the previous example, strings can be initialized with any valid string literal, just like numerical type variables can be initialized to any valid numerical literal. As with fundamental types, all initialization formats are valid with strings:
|
|
Strings can also perform all the other basic operations that fundamental data types can, like being declared without an initial value and change its value during execution:
// my first string
#include <iostream>
#include <string>
using namespace std;
int main ()
{
string mystring;
mystring = "This is the initial string content";
cout << mystring << endl;
mystring = "This is a different string content";
cout << mystring << endl;
return 0;
}
printout:
This is the initial string content
This is a different string content
Note: inserting the endl
manipulator ends the line
(printing a newline character and flushing the stream). The string class is a compound type. As you can see in the
example above, compound types are used in the same way as
fundamental types: the same syntax is used to declare
variables and to initialize them.