Difference between revisions of "CPP/Struct"

From ProgrammingExamples
< CPP
Jump to: navigation, search
(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>')
 
(Struct.cpp)
Line 2: Line 2:
 
<source lang="cpp">
 
<source lang="cpp">
 
#include <iostream>
 
#include <iostream>
 +
#include <string>
  
struct Card
+
using namespace std;
{
+
  int id;
+
};
+
  
int main (int argc, char *argv[])
+
/*
 +
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
 
{
 
{
   Card c;
+
private:
   c.id = 3;
+
   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;
 
   return 0;
 
   return 0;
 
}
 
}

Revision as of 00:15, 29 June 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;
  return 0;
}