Itban Saeed
Itban Saeed

Reputation: 1666

Error C2678: binary '<<' : no operator found which takes a left-hand operand of type 'const std::ofstream' (or there is no acceptable conversion)

I am working on an MFC Application and have declared an ofstream object in a class header, the object is then initialized in the constructor and used in the other methods of the same class. I got the following error:

Error C2678: binary '<<' : no operator found which takes a left-hand operand of type 'const std::ofstream' (or there is no acceptable conversion)

I have searched about this issue and found many solutions i.e. there are some suggestions to:

And some other information that I got is about when does this error occur. But all that I got doesn't fix my issue. Kindly have a look at my code:

CGroupComboBox.h :

private:
    std::ofstream fptr;

CGroupComboBox.cpp :

//Constructor
CGroupComboBox::CGroupComboBox()
    : m_dropdownListAutoWidth(true)
    , m_autocomplete(true)
    , m_selectionUndoByEscKey(true)
{
    fptr.open("test.txt",std::ios::out); //Initialization of fptr
}

//Member Function
int CGroupComboBox::FindString(int nStartAfter, LPCTSTR lpszString) const
{
    fptr<<"I am FindString.\n"; //Trying to write something

    //Other Code
}

//Destructor
CGroupComboBox::~CGroupComboBox()
{
    //Other Code

    fptr.close();
}

What am I doing wrong here?

Upvotes: 3

Views: 10591

Answers (3)

Vlad from Moscow
Vlad from Moscow

Reputation: 311038

You declared this member function with qualifier const

int CGroupComboBox::FindString(int nStartAfter, LPCTSTR lpszString) const
                                                                    ^^^^^

Thus this in this case has type const CGroupComboBox * and you may not change data member of the object pointed to by this.

However this statements

fptr<<"I am FindString.\n"; //Trying to write something

requires non-const data member fptr.

So the compiler issues an error.

One of solutions is to use specifier mutable for data member fptr

Upvotes: 4

hellow
hellow

Reputation: 13440

Error C2678: binary '<<' : no operator found which takes a left-hand operand of type 'const std::ofstream' (or there is no acceptable conversion)

That is the answer. << tries to manipulate the object and your object is const.

To solve the problem, remove const from you FindString method

Upvotes: 1

David Schwartz
David Schwartz

Reputation: 182779

Since fptr can be modified from const-qualified functions, it should be marked mutable. Alternatively, you can use a const_cast in FindString.

Upvotes: 4

Related Questions