Skip to content

Instantly share code, notes, and snippets.

@mihids
Last active August 29, 2015 14:02
Show Gist options
  • Save mihids/1f109d36391ef6da4a8d to your computer and use it in GitHub Desktop.
Save mihids/1f109d36391ef6da4a8d to your computer and use it in GitHub Desktop.
A freind fnction and a friend class
// A freind function
class A;
class B
{
private:
int i_Num;
public:
B(int iNum) { i_Num = iNum; }
friend void PrintNumbers(A &a, B &b); // non-member function, cannot use this
};
class A
{
private:
int i_Num;
public:
A(int iNum) { i_Num = iNum; }
friend void PrintNumbers(A &a, B &b);
};
void PrintNumbers(A &a, B &b)
{
std::cout << "A number is " << a.i_Num <<
" and the B number is " << b.i_Num << std::endl;
}
// A freind class
class B
{
private:
int i_Num;
public:
B(int iNum) { i_Num = iNum; }
friend class A;
};
class A {
private:
int i_Num;
public:
void PrintNumbers(B &b) {
std::cout << "A number is " << i_Num <<
" and the B number is " << b.i_Num << std::endl; // accessing the private member of B
}
}
#include <iostream>
#include <ctime>
#include <sstream>
#include <fstream>
using namespace std;
// timestamp returns the current time as a string
std::string timestamp();
class LogStatement;
ostream& operator<<(ostream& ost, const LogStatement& ls);
class LogStatement {
public:
LogStatement(std::string s) : data(s), time_string(timestamp()) {
};
//This method handles all the outputs.
friend ostream& operator<<(ostream&, const LogStatement&);
private:
std::string data;
std::string time_string;
};
ostream& operator<<(ostream& ost, const LogStatement& ls) {
ost << "~|" << ls.time_string << '|' << ls.data << "|~";
return ost;
}
std::string timestamp() {
//Notice the use of a stringstream, yet another useful stream medium!
ostringstream stream;
time_t rawtime;
tm * timeinfo;
time(&rawtime);
timeinfo = localtime(&rawtime);
stream << (timeinfo->tm_year) + 1900 << " " << timeinfo->tm_mon
<< " " << timeinfo->tm_mday << " " << timeinfo->tm_hour
<< " " << timeinfo->tm_min << " " << timeinfo->tm_sec;
// The str() function of output stringstreams return a std::string.
return stream.str();
}
/*
*
*/
int main(int argc, char** argv) {
char* testArr[3] = {"log 1", "log 2", "log 3"};
ostringstream log_data;
// This takes all the char arrays in the argv
// (except the filename) and produces a stream.
for (int i = 0; i < 3; i++) {
log_data << testArr[i] << ' ';
}
int iAnyNum=100;
log_data << iAnyNum;
LogStatement log_entry(log_data.str());
clog << log_entry << endl;
ofstream logfile("logfile", ios::app);
// check for errors opening the file
if (!logfile) {
return -1;
}
logfile << log_entry << endl;
logfile.close();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment