Last active
October 4, 2020 22:28
-
-
Save patgarner/331a2bdf74b65934a74eaee0ba35b8ad to your computer and use it in GitHub Desktop.
Example C++ class that demonstrates combined declaration and definition of class within single file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <algorithm> | |
#include <iostream> | |
#include <string> | |
using namespace std; | |
class Test { | |
public: | |
Test(string name) : name(fixName(name)) {} | |
friend Test operator+(Test& lhs, Test& rhs) { | |
string str = lhs.name + rhs.name; | |
random_shuffle(str.begin(), str.end()); | |
return Test(str); | |
} | |
friend ostream& operator<<(ostream& os, const Test& t) { | |
os << t.name; | |
return os; | |
} | |
friend istream& operator>>(istream& is, Test& t) { | |
is >> t.name; | |
return is; | |
} | |
static string fixName(string name) { | |
// convert string to lower case | |
for (string::iterator it = name.begin(); it < name.end(); it++) { | |
*it = tolower(*it); | |
} | |
// make the first character upper case | |
name[0] = toupper(name[0]); | |
return name; | |
} | |
private: | |
string name; | |
}; | |
int main() { | |
cout << endl; | |
Test t("Fred"); | |
cout << "New Test named " << t << endl; | |
cout << "Enter new name for " << t << ": "; | |
cin >> t; | |
cout << "Test now named " << t << endl; | |
cout << endl; | |
Test s("George"); | |
cout << "Another new Test named " << s << endl; | |
cout << t << " + " << s << " = " << t + s << endl; | |
cout << endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment