Skip to content

Instantly share code, notes, and snippets.

@patgarner
Last active October 4, 2020 22:28
Show Gist options
  • Save patgarner/331a2bdf74b65934a74eaee0ba35b8ad to your computer and use it in GitHub Desktop.
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.
#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