user2556923
user2556923

Reputation: 11

How to fix type qualifiers errors in classes?

This is my main.cpp code. The input is 3 strings and the output Prints out the value and length of the 3 String objects passed to it

void Display(const String &str1, const String &str2, const String &str3)
{
  cout << "str1 holds \"";
  str1.print(); // the error is here about the str1
  cout.flush();
  cout << "\" (length = " << str1.length() << ")" << endl;

  cout << "str2 holds \"";
  str2.print();
  cout.flush();
  cout << "\" (length = " << str2.length() << ")" << endl;

  cout << "str3 holds \"";
  str3.print();
  cout.flush();
  cout << "\" (length = " << str3.length() << ")" << endl;
}

This is the error:

Error C2662: 'String::print' : cannot convert 'this' pointer from 'const String' to 'String &'

This is in my implementation file file: Did I do something wrong here?

void String::print()
{
cout << m_pName << ": ";
cout << (int)m_str1 << ", ";
cout << (int)m_str2 << ", ";
cout << (int)m_str3 << endl;
}

Upvotes: 1

Views: 1711

Answers (1)

masoud
masoud

Reputation: 56479

str1 is a reference to a const String.

In simple words, compiler wants to make sure str1.print() will not modify the str1.

Therefore, it looks for a const overload of print method which doesn't exist.

Make the print method const:

class String
{
   ...

   void print() const;
                ^^^^^^
   ...
};


void String::print() const
{                    ^^^^^
...
}

Upvotes: 2

Related Questions