C ++ believes that "<<" is not a member of the class, but it is

I need to write a simple log class that will write output to a file.

I want it to work with operator overloading, so I can do this:

MyLog log("C:\\log.txt");
log<<"Message";

But Visual C ++ tells me: "error C2039: '<<: is not a member of" MyLog "

I do not know what I am doing wrong.

Here is the code:

Mylog.h

#pragma once
#include <iostream>
#include <conio.h>
#include <fstream>
using namespace std;

class MyLog
{
private:
    ofstream logfile;
public:
    MyLog(char* filename);
    friend MyLog& operator<<(MyLog& l,char*msg);
};

Mylog.cpp

#include "MyLog.h"

MyLog::MyLog(char* filename)
{
    logfile.open(filename);
}

MyLog& MyLog::operator<<(MyLog& l,char*msg)
{
    cout<<msg;
    return l;
}

Does anyone know what is wrong?

+3
source share
6 answers

You declared a free function MyLog& operator<<(MyLog& l,char* msg)as a friendclass MyLog. It is not a member of the class itself, so your function definition should begin with this:

MyLog& operator<<(MyLog& l,char* msg)
{
   //...
+19

Visual ++ , operator<< MyLog. - :

class MyLog {
    // ...

public:
    MyLog& operator<<(int i);
}

MyLog& MyLog::operator<<(int i) {
    cout << i;
    return *this;
}
+2

char *:

< < "";

int:

MyLog & MyLog:: operator < (MyLog & l, int i)

, " "

0

<< int, char *.

char *:

MyLog& operator<<(MyLog& l,char* msg);
, friend?
0

friend MyLog& operator<<(MyLog& l,int i);

MyLog& operator<<(MyLog& l,int i);
0

< < , MyLog. :

MyLog & < (MyLog & l, int i) {    <

0

Source: https://habr.com/ru/post/1718529/


All Articles