FAQ 2.14 What are the basics of using classes that contain overloaded operators?

graphics/new_icon.gif

They're easy to use. But when you create your own, make sure the operators are intuitive and natural.

Here is an example that uses the standard string class:

 #include <iostream> #include <string>                                    <-- 1 using namespace std; void f(const string& firstName, const string& lastName) {   string fullName = firstName + " " + lastName;      <-- 2   cout << "Your full name is " << fullName << "\n";   <-- 3 } int main() {   f("Charlie", "Brown");   f("Fred", "Flintstone"); } 

(1) Defines class string

(2) Line 1

(3) Line 2

The f() function takes two string objects that will remain unchanged (const string&; see FAQ 2.09).

Line 1 concatenates the first name, a space, and then the last name. This uses the overloaded + operator associated with class string.

Line 2 prints the resulting full name. This uses the overloaded << operator associated with class string.



C++ FAQs
C Programming FAQs: Frequently Asked Questions
ISBN: 0201845199
EAN: 2147483647
Year: 2005
Pages: 566
Authors: Steve Summit

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net