In this part of my C++ tutorial we’ll cover Operator Overloading, File I/O and will present you with another problem to solve. We’ll learn to use unary and Binary operators. We’ll specifically overload ++, print customer strings, +, [], ==, <, >, and =. Then we’ll write and read from files.
All of the code and a transcript follows the video below. I hope you enjoy the tutorial.
If you like tutorials like this, consider donating $1, or simply turn off Ad Blocking software when watching my videos. Either helps me to keep my videos 100% free.
Code & Transcript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 |
// ---------- C++ TUTORIAL 12 ---------- // ---------- OPERATOR OVERLOADING ---------- #include <cstdlib> #include <iostream> #include <string> #include <vector> #include <ctime> #include <numeric> #include <cmath> // Needed for ostringstream #include <sstream> // Create a custom Box class with overloaded operators class Box{ public: double length, width, breadth; // Used to hold a string representation of a box std::string boxString; Box(){ length = 1, width = 1, breadth = 1; } Box(double l, double w, double b){ length = l, width = w, breadth = b; } // You can define customer operators just like // you define functions // This is a unary operator because it operates // on 1 object // Other Unary Operators : --, *(pointer dereference), // -> (Member Selection), !, & (Address of), +, - Box& operator ++ (){ length++; width++; breadth++; return *this; } // Creates a C string representation which is a // pointer to an array that is null terminated operator const char*() { // Creates a stream that can be loaded with // characters that can then be accessed as // a string object std::ostringstream boxStream; boxStream << "Box : " << length << ", " << width << ", " << breadth; // Return a string representation of the stream boxString = boxStream.str(); // Returns the pointer to the string array return boxString.c_str(); } // Binary operators operate on 2 objects // +, -, *, /, %, ==, !=, >, <, >=, <=, &&, ||, // !, =, +=, -=, *=, /=, ^, [], &, | // Let's add boxes Box operator + (const Box& box2){ Box boxSum; boxSum.length = length + box2.length; boxSum.width = width + box2.width; boxSum.breadth = breadth + box2.breadth; return boxSum; } // Access items using a subscript operator double operator [] (int x){ if(x == 0){ return length; } else if(x == 1){ return width; } else if(x == 2){ return breadth; } else { return 0; } } // Check for box equality bool operator == (const Box& box2){ return ((length == box2.length) && (width == box2.width) && (breadth == box2.breadth)); } // Check for which is bigger bool operator < (const Box& box2){ double thisSize = length + width + breadth; double box2Size = box2.length + box2.width + box2.breadth; if (thisSize < box2Size){ return true; } else { return false; } } bool operator > (const Box& box2){ double thisSize = length + width + breadth; double box2Size = box2.length + box2.width + box2.breadth; if (thisSize > box2Size){ return true; } else { return false; } } // Overload the assignment operator void operator = (const Box& boxToCopy){ length = boxToCopy.length; width = boxToCopy.width; breadth = boxToCopy.breadth; } }; int main() { Box box(10,10,10); // Will increment all values in the box by 1 ++box; std::cout << box << "\n"; // Add boxes Box box2(5,5,5); std::cout << "Box1 + Box2 = " << box + box2 << "\n"; // Access data with subscript operator std::cout << "Box Length : " << box[0] << "\n"; // Displays true or false for bolleans std::cout << std::boolalpha; std::cout << "Are boxes equal : " << (box == box2) << "\n"; // Is box < box2 std::cout << "Is box < box2 : " << (box < box2) << "\n"; // Is box > box2 std::cout << "Is box < box2 : " << (box > box2) << "\n"; box = box2; std::cout << box << "\n"; return 0; } // ---------- OPERATOR OVERLOADING ---------- // ---------- FILE I/O & PROBLEM ---------- #include <cstdlib> #include <iostream> #include <string> #include <vector> #include <ctime> #include <numeric> #include <cmath> #include <sstream> // iostream allows use to read from the standard // input (keyboard) and write to the standard output // (console) // fstream is needed for working with files #include <fstream> // ----- PROBLEM FUNCTION PROTOTYPE ----- std::vector<std::string> StringToVector(std::string, char separator); // ----- END OF PROBLEM FUNCTION PROTOTYPE ----- int main() { std::ofstream writeToFile; std::ifstream readFromFile; std::string txtToWrite = ""; std::string txtFromFile = ""; // We open the file by providing a name and then either // ios::app : Append to the end of the file // ios::trunc : If the exists delete content // ios::in : Open file for reading // ios::out : Open file for writing // ios::ate : Open writing and move to the end of the file writeToFile.open("test.txt", std::ios_base::out | std::ios_base::trunc); if(writeToFile.is_open()){ // You can write with the stream insertion operator writeToFile << "Beginning of File\n"; // You can write data in a string std::cout << "Enter data to write : "; getline(std::cin, txtToWrite); writeToFile << txtToWrite; // Close the file writeToFile.close(); } // Open the file for reading readFromFile.open("test.txt", std::ios_base::in); if(readFromFile.is_open()){ // Read text from file while(readFromFile.good()){ getline(readFromFile, txtFromFile); // Print text from file std::cout << txtFromFile << "\n"; // ----- PROBLEM ----- // After each line print both the number of // words in each line and the average word length std::vector<std::string> vect = StringToVector(txtFromFile, ' '); int wordsInLine = vect.size(); std::cout << "Words in Line : " << wordsInLine << "\n"; int charCount = 0; for(auto word: vect){ for(auto letter: word){ charCount++; } } int avgNumChars = charCount/wordsInLine; std::cout << "Avg Word Length : " << avgNumChars << "\n"; // ----- END OF PROBLEM ----- } readFromFile.close(); } return 0; } // ----- PROBLEM FUNCTION ----- std::vector<std::string> StringToVector(std::string theString, char separator){ // Create a vector std::vector<std::string> vecsWords; // A stringstream object receives strings separated // by a space and then spits them out 1 by 1 std::stringstream ss(theString); // Will temporarily hold each word in the string std::string sIndivStr; // While there are more words to extract keep // executing // getline takes strings from a stream of words stored // in the stream and each time it finds a blanks space // it stores the word proceeding the space in sIndivStr while(getline(ss, sIndivStr, separator)){ // Put the string into a vector vecsWords.push_back(sIndivStr); } return vecsWords; } // ----- END OF PROBLEM FUNCTION ----- // ---------- FILE I/O & PROBLEM ---------- |
Leave a Reply