C++ 认为 '<<' 不是类的成员,但它是

标签 c++ operator-overloading

我必须编写一个简单的日志类,它将输出写入一个文件。

我希望它与重载 << 运算符一起工作,所以我可以这样做:

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

但是 Visual C++ 告诉我:“error C2039: '<<' : is not a member of 'MyLog'”

我不知道我做错了什么。

代码如下:

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);
};

我的日志.cpp

#include "MyLog.h"

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

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

谁知道哪里出了问题?

最佳答案

您已经声明了自由函数 MyLog& operator<<(MyLog& l,char* msg)成为friendMyLog类(class)。它不是类本身的成员,因此您对函数的定义应以此开头:

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

关于C++ 认为 '<<' 不是类的成员,但它是,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1475992/

相关文章:

c++ - 用户输入字符串的耦合算法

c++ - static_assert c++11 的可用性

c++ - 构造线程时调用的运算符重载函数

c++ - 为什么我的赋值运算符不能用于自赋值?

C++ 指针数据成员 : Who should delete them?

c++ - 在 C++ 中使用 "set/p"

c++ - 纯虚拟运营商

C++ "="具有私有(private) vector 和迭代器的类的运算符行为

c++ - 无法解析基于模板的标识符 "get".Netbeans 8.1

c++ - 如何在同一个类中使用重载运算符 []?