Skip to content

Instantly share code, notes, and snippets.

Created March 23, 2015 05:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/06b9251a37008d158f59 to your computer and use it in GitHub Desktop.
Save anonymous/06b9251a37008d158f59 to your computer and use it in GitHub Desktop.
C++ swap
#include <iostream>
#include <string>
using namespace std;
class A {
private:
string name;
public:
A(string newName) {
name = newName;
}
void SayHi() {
cout << "Hello from " << name << endl;
}
};
void swap(A& a1, A& a2) {
A temp = a1;
a1 = a2;
a2 = temp;
}
void setA3ByValue() {
A a1("Dog");
A a2("Cat");
A a3 = a1;
swap(a1,a2);
a1.SayHi();
a2.SayHi();
a3.SayHi();
}
void setA3ByReference() {
A a1("Dog");
A a2("Cat");
A& a3 = a1;
swap(a1,a2);
a1.SayHi();
a2.SayHi();
a3.SayHi();
}
int main() {
setA3ByValue();
setA3ByReference();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment