C++ 如何修复类中的类型限定符错误?

C++ 如何修复类中的类型限定符错误?,c++,C++,这是我的main.cpp代码。输入是3个字符串,输出打印出传递给它的3个字符串对象的值和长度 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 <<

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

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;
}
void显示(常量字符串和str1、常量字符串和str2、常量字符串和str3)
{

cout
str1
是对常量的引用

简单地说,编译器希望确保
str1.print()
不会修改
str1

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

使
打印
方法
const

class String
{
   ...

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


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

str1
是对
常量的引用

简单地说,编译器希望确保
str1.print()
不会修改
str1

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

使
打印
方法
const

class String
{
   ...

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


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

使
print()
a
const
-限定成员函数:
void print()const
(int)m_str1
看起来非常狡猾。至少使用C++风格的强制转换,并将变量名更改为有意义的名称。编程中有一条规则叫DRY——不要重复自己的代码,你的代码会严重破坏它。让display一次处理一个字符串,这样你就不用修改同样的内容三次(或者修改一次,忘记另外两个,想知道为什么它不起作用…@aryjczyk我从来没有听说过这个“枯燥规则”。谢谢你的提示。Make
print()
a
const
-限定成员函数:
void print()const
(int)m_str1
看起来非常狡猾。至少使用C++风格的强制转换,并将变量名更改为有意义的名称。编程中有一条规则叫DRY——不要重复自己的代码,你的代码会严重破坏它。让display一次处理一个字符串,这样你就不用修改同样的内容三次(或者修改一次,忘记另外两个,想知道为什么它不起作用…@aryjczyk我从来没听说过这个“枯燥规则”。谢谢你的提示。