1

这是我的 main.cpp 代码。输入是 3 个字符串,输出打印出传递给它的 3 个 String 对象的值和长度

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

这是错误:

错误 C2662:“String::print”:无法将“this”指针从“const String”转换为“String &”

这是在我的实现文件中:我在这里做错了吗?

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

1 回答 1

1

str1是对 a 的引用。const String

简单来说,编译器要确保str1.print()不会修改str1.

因此,它会寻找不存在const的方法重载。print

制作print方法const

class String
{
   ...

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


void String::print() const
{                    ^^^^^
...
}
于 2013-07-06T20:12:35.130 回答