Created
March 23, 2015 05:34
-
-
Save anonymous/06b9251a37008d158f59 to your computer and use it in GitHub Desktop.
C++ swap
This file contains 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 <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