overload operator<< for class Personal


👍 g++ personal.cpp database.cpp
👍 ./a.out
1. Add 2. Find 3. Modify a rec 4. Exit
Enter an option: 1
SSN: 123456789
in operator<<
Enter an option: 4

👍 cat personal.h
#ifndef PERSONAL
#define PERSONAL

using namespace std;
class Personal {
public:
  Personal();
protected:
  char SSN[10];
  friend ostream& operator<<(
    ostream &o, Personal &p) {
    o << "in operator<<";
    return o;
  }
  istream& readFromConsole(istream&);
  friend istream& operator>>(
    istream &i, Personal &p) {
    return p.readFromConsole(i);
  }
};
#endif

👍 cat personal.cpp 
#include <iostream>
#include "personal.h"
Personal::Personal(){
}
istream& Personal::readFromConsole(
  istream &i){
  SSN[9] = '\0';
  char s[80];
  cout << "SSN: ";
  i.getline(s, 80);
  strncpy(SSN, s, 9);
  return i;
}

👍 cat database.h 
#ifndef DATABASE
#define DATABASE

template <typename T>
class Database {
public:
  Database();
  void run();
};
#endif

👍 cat database.cpp
#include <iostream>
#include "personal.h"
#include "database.h"

template <typename T>
Database<T>::Database() {
}

template <typename T>
void Database<T>::run() {
  char option[5];
  T rec;
  cout << "1. Add "
       << "2. Find "
       << "3. Modify a record "
       << "4. Exit\n";
  cout << "Enter an option: ";
  while (cin.getline(option, 4)) {
    if (*option == '1') {
      cin >> rec;
      cout << rec;
    } else if (*option == '2') {
    } else if (*option == '3') {
    } else if (*option != '4')
      cout << "Wrong option\n";
    else return;
    cout << "Enter an option: ";
  }
}

int main() {
  Database<Personal>().run();
}

    

ch 1.10 CASE STUDY: RANDOM ACCESS FILE p43 of

© 拇指 2023