Difference between revisions of "CPP/Struct"
From ProgrammingExamples
< CPP
Daviddoria (Talk | contribs) (Created page with '==Struct.cpp== <source lang="cpp"> #include <iostream> struct Card { int id; }; int main (int argc, char *argv[]) { Card c; c.id = 3; return 0; } </source>') |
FirstPerson (Talk | contribs) (→Struct.cpp) |
||
(One intermediate revision by the same user not shown) | |||
Line 2: | Line 2: | ||
<source lang="cpp"> | <source lang="cpp"> | ||
#include <iostream> | #include <iostream> | ||
+ | #include <string> | ||
− | + | using namespace std; | |
− | + | ||
− | + | ||
− | + | ||
− | + | /* | |
+ | Use the keyword struct to declare a struct | ||
+ | Syntax: struct structVariableName { content }; | ||
+ | |||
+ | Struct and classes are very similar in C++, the ONLY difference | ||
+ | is that struct by default is set to public while class is set | ||
+ | to private by default. | ||
+ | |||
+ | Below shows an example of one of many usuage of struct. Examples are | ||
+ | kept simple as possible. | ||
+ | */ | ||
+ | struct IntStringPair | ||
{ | { | ||
− | + | private: | |
− | + | int m_first; | |
+ | string m_second; | ||
+ | public: | ||
+ | IntStringPair(const int intVal = 0, const string& strVal = "") | ||
+ | : m_first(intVal), m_second(strVal) | ||
+ | { | ||
+ | } | ||
+ | int& first(){ return m_first; } | ||
+ | string& second(){ return m_second; } | ||
+ | }; | ||
+ | int main (){ | ||
+ | IntStringPair card = IntStringPair(10,"clubs"); | ||
+ | cout << card.first() << " of " << card.second() << endl; | ||
+ | card.first() = 3; | ||
+ | card.second() = "hearts"; | ||
+ | cout << card.first() << " of " << card.second() << endl; | ||
return 0; | return 0; | ||
} | } |
Latest revision as of 20:09, 12 July 2010
Struct.cpp
#include <iostream> #include <string> using namespace std; /* Use the keyword struct to declare a struct Syntax: struct structVariableName { content }; Struct and classes are very similar in C++, the ONLY difference is that struct by default is set to public while class is set to private by default. Below shows an example of one of many usuage of struct. Examples are kept simple as possible. */ struct IntStringPair { private: int m_first; string m_second; public: IntStringPair(const int intVal = 0, const string& strVal = "") : m_first(intVal), m_second(strVal) { } int& first(){ return m_first; } string& second(){ return m_second; } }; int main (){ IntStringPair card = IntStringPair(10,"clubs"); cout << card.first() << " of " << card.second() << endl; card.first() = 3; card.second() = "hearts"; cout << card.first() << " of " << card.second() << endl; return 0; }