template <classT> classArray { int size; T *data; public: Array(int s) { size = s; data = new T[s]; }
~Array() { delete []data; }
T &operator [] (int i) { if (i < 0 || i >= size) { // cerr << endl << "Index out of range" << endl; // exit(EXIT_FAILURE); throw"Index out of range"; } else { return data[i]; } } };
structDate { short year = 1900; short month = 1; short day = 1; };
structMovie { string title; Date releaseDate; bool isPopular = true;
// Overloading == operator in struct booloperator==(const Movie &movie) const { // title = "a"; // can not modify, because the method is const // movie.title = "a"; // can not modify, because the parameter is const return title == movie.title; } };
// Overloading == operator out struct // bool operator==(const Movie &first, const Movie &second) // { // return first.title == second.title; // }
intmain() { int x = 1; double y = 2.2; int z = x + y; cout << z << endl; // 3
z = x + (int)y; cout << z << endl; // 3
z = x + static_cast<int>(y); cout << z << endl; // 3
// TODO // Since in a 4-byte pointer, it is pointing to 1-byte of allocated memory, // it may generate runtime error or will overwrite some adjacent memory. char c = 65; // 1-byte data. ASCII of 'A' int *ptr = (int *)&c; // 4-byte cout << ptr << endl;
// In C++ the static_cast<>() only converts between compatible types. // If not it will raise incorrect pointer assignment exception during compilation. // int *ptr2 = static_cast<int>(&c); // invalid type conversion
intmain(){ string nameSeed = "ABCDE"; for (int i = 0; i < 5; i++) { string name = "Player "; name += nameSeed[i]; // OK // name.append(nameSeed[i]); // error, not has string& append(const char s); func // name.append(&nameSeed[i]); // append all chars the pointer point to // Player ABCDE // Player BCDE // Player CDE // Player DE // Player E // name.append(&nameSeed[i], 1); // OK // name.append(&nameSeed[i], 0, 1); // ok // name = name + nameSeed[i]; // OK // name = "Player " + nameSeed[i]; // Not Correct ?? cout << name << endl; } return0; }
intaddFunc(int a, int b){ return a + b; } intaddFunc(double a, double b){ return a + b; }
intmain() { fun(); return0; }
// $ gcc -c cfile.c // $ nm cfile.o // 0000000000000000 b .bss // 0000000000000000 d .data // 0000000000000000 p .pdata // 0000000000000000 r .rdata // 0000000000000000 r .rdata$zzz // 0000000000000000 t .text // 0000000000000000 r .xdata //! 0000000000000000 T fun // U puts
// $ g++ -c app.cpp // $ nm app.o // 0000000000000000 b .bss // 0000000000000000 d .ctors // 0000000000000000 d .data // 0000000000000000 p .pdata // 0000000000000000 r .rdata$.refptr.__dso_handle // 0000000000000000 r .rdata$.refptr._ZNSt8ios_base4InitD1Ev // 0000000000000000 r .rdata$zzz // 0000000000000000 R .refptr.__dso_handle // 0000000000000000 R .refptr._ZNSt8ios_base4InitD1Ev0000000000000000 t .text // 0000000000000000 r .xdata // U __cxa_atexit // U __dso_handle // U __main // 00000000000000a2 t _GLOBAL__sub_I__Z7addFuncii //! U _Z3funv // 000000000000004f t _Z41__static_initialization_and_destruction_0ii //! 0000000000000014 T _Z7addFuncdd //! 0000000000000000 T _Z7addFuncii // U _ZNSt8ios_base4InitC1Ev // U _ZNSt8ios_base4InitD1Ev // 0000000000000000 b _ZStL8__ioinit // 0000000000000032 T main
// $ g++ -c app.cpp // $ nm app.o // 0000000000000000 b .bss // 0000000000000000 d .ctors // 0000000000000000 d .data // 0000000000000000 p .pdata // 0000000000000000 r .rdata$.refptr.__dso_handle // 0000000000000000 r .rdata$.refptr._ZNSt8ios_base4InitD1Ev // 0000000000000000 r .rdata$zzz // 0000000000000000 R .refptr.__dso_handle // 0000000000000000 R .refptr._ZNSt8ios_base4InitD1Ev0000000000000000 t .text // 0000000000000000 r .xdata // U __cxa_atexit // U __dso_handle // U __main // 00000000000000a2 t _GLOBAL__sub_I__Z7addFuncii // 000000000000004f t _Z41__static_initialization_and_destruction_0ii //! 0000000000000014 T _Z7addFuncdd //! 0000000000000000 T _Z7addFuncii // U _ZNSt8ios_base4InitC1Ev // U _ZNSt8ios_base4InitD1Ev // 0000000000000000 b _ZStL8__ioinit //! U fun // 0000000000000032 T main
// $ g++ app.o cfile.o && ./a.exe // I am in c file
// $ g++ -c cfile.c // $ nm cfile.o // 0000000000000000 b .bss // 0000000000000000 d .data // 0000000000000000 p .pdata // 0000000000000000 r .rdata // 0000000000000000 r .rdata$zzz // 0000000000000000 t .text // 0000000000000000 r .xdata //! 0000000000000000 T _Z3funv // U puts
// If use g++ comile cfile.c will not occurs error even if not use `extern 'C'` // g++ app.cpp cfile.c && ./a.exe // I am in c file
# Why == overloading can access private members of argument
Your operator== is a member of your Group class. Member functions can access any private members of that class, not only for this, but for any instance they can access.
If you think about it this behaviour is necessary, because otherwise access control would make methods for interaction of two or more instances (swap, copy constructors, operators) impossible, unless the object has a public accessor to any member variable, which is used in such a method.
Often enough that isn’t desirable from a design point of view. Furthermore it would raise the bar for access control to high (“if I simply make that member public, I can spare me the pain…”).
// regex_match(mystr, cm, str_expr, regex_constants::match_default);
// string mystr = "She sells_sea shells in the sea shore"; // regex regexp("s[a-z_]+"); // smatch sm; // regex_search(mystr, sm, regexp); // for (auto i : sm) // { // cout << i << endl; // }
string mystr = "This is software testing Help portal \n";
cout << "Input string: " << mystr << endl;
// regex to match string beginning with 'p' regex regexp("p[a-zA-z]+"); cout << "Replace the word 'portal' with word 'website' : "; // regex_replace() for replacing the match with the word 'website' cout << regex_replace(mystr, regexp, "website");
string result; cout << "Replace the word 'website' back to 'portal': "; // regex_replace( ) for replacing the match back with 'portal' // TODO back_inerter regex_replace(back_inserter(result), mystr.begin(), mystr.end(), regexp, "portal");
cout << result;
string input; regex integer_expr("(\\+|-)?[[:digit:]]+"); while (true) { cout << "Enter the input: "; cin >> input; if (input == "q") break;
if (regex_match(input, integer_expr)) cout << input << " is an integer" << endl; else cout << "Invalid input: Not an integer" << endl; }
// This function make_move_iterator() was introduced first in the C++ 11 version. // This function returns move_iterator for the specified iterator iter and the type will be deduced from the argument type. // Note: This method is different from move() & back_inserter // because the insert() function might allocate enough memory to store all the elements in a single allocation. // But when we use back_inserter() that is equal to multiple push_back() which will do multiple allocations. // TODO Different with first.insert(first.end(), second.begin(), second.end());? first.insert(first.end(), make_move_iterator(second.begin()), make_move_iterator(second.end())); print_vector(first);
#define STRING(number) STR(number) #define STR(number) #number #define NUMBER 9876.5412
usingnamespacestd;
// Note : The string returned is only a temporary object and if other methods are called on the results, then it will yield a dangling pointer. stringConvert(float number) { ostringstream buff; buff << fixed << setprecision(4) << number; return buff.str(); }
// Note: This function can return unexpected output because the number of significant digits in the string returned by it can be zero as well and it can be seen in code. // Enter the float number to convert to string: 58.25828 // After Converting to String : 58.258282 float f; cout << "Enter the float number to convert to string: "; cin >> f; stringfloat_string(to_string(f)); if (float_string.empty()) { cout << "Empty Number!!"; } cout << "After Converting to String: " << float_string << endl;
if (isValidName(name)) { cout << "The name entered is " << name << endl; } else { cout << "Enter a valid name!" << endl; }
int age; while (true) { cout << "Enter the age: "; cin >> age; if (cin.fail()) { cout << "Enter valid age!\n"; cin.clear(); // clear the failed state cin.ignore(numeric_limits<streamsize>::max(), '\n'); // ignore() is used to clear the wrong input entered buffer continue; }
// For clearing additional input like: 23abc(here abc is addtional) // remove the additional input from the stream cin.ignore(numeric_limits<streamsize>::max(), '\n');
// Returns the number of characters extracted by the last unformatted input operation performed on the object.
// The unformatted input operations that modify the value returned by this function are those performed by the following member functions: get, getline, ignore, peek, read, readsome, putback and unget. //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ // Notice though, that peek, putback and unget do not extract characters. So gcount will always return zero after a call to any of these. // it will return more than 1 if there is something which is not extracted properly // if input 23abc, 23 will extract to age, cin.ignore(numeric_limits<streamsize>::max(), '\n'); ignore the buffer abc\n // so if cin.gcount() > 1 represents except int and '\n' has other character if (cin.gcount() > 1) { cout << "Enter valid age!!\n"; continue; }
Conversion int to short use c++ style initial method will occurs narrowing conversion but c style without warning.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include<iostream>
usingnamespacestd;
intmain() { int a = 100'000'000; short b = a; // no warning cout << b << endl; short c{a}; // warning: narrowing conversion of 'a' from 'int' to 'short int' [-Wnarrowing] cout << c << endl; // -7936 // -7936