By Hector M Lugo-Cordero September 17, 2008 Structs By Hector M Lugo-Cordero September 17, 2008 Department of Electrical and Computer Engineering
The Department of Electrical and Computer Engineering Outline Creation Usage Enhancing The Department of Electrical and Computer Engineering
The Department of Electrical and Computer Engineering Creation Syntax struct <name>{ Fields [Methods] }; Just like objects (to be discussed) structs allow operator overloading in C++ (not in C) The Department of Electrical and Computer Engineering
The Department of Electrical and Computer Engineering Creation (cont.) Example: struct Pair{ double first; double second; Pair(){ first = 0; second = 0; } Pair(double x, double y){ first = x; second = y; bool equal(Pair other){ return (first == other.first) && (second == other.second); }; The Department of Electrical and Computer Engineering
The Department of Electrical and Computer Engineering Usage int main(int argc, char** argv) { Pair myPair(5, 2); //sometimes struct Pair myPair cout << “(“ << myPair.first << “, “ << myPair.second << “)” << endl; Pair test; test.first = 5; Test.second = 2; if(myPair.equal(test)){ cout << “Enter a new pair: ” << endl; cin >> test.first; cin >> test.second; //input is read x y } return 0; IS THERE AN EASIER WAY? :S YES :P The Department of Electrical and Computer Engineering
The Department of Electrical and Computer Engineering Enhancing Operator overloading bool operator==(Pair& other){ return (first == other.first) && (second == other.second); } friend ostream& operator<<(otstream& out, Pair data){ out << “(“ << data.first << “, “ << data.second << “)”; return out; The Department of Electrical and Computer Engineering
The Department of Electrical and Computer Engineering Questions? ? The Department of Electrical and Computer Engineering