【问题标题】:How to remove this fpermissive error in c++?如何在 C++ 中删除这个 fpermissive 错误?
【发布时间】:2021-05-08 13:45:15
【问题描述】:

将“const IntBag”作为“this”参数传递会丢弃限定符 [-fpermissive]

这是我的代码: '''C++ **

> int IntBag::operator[](int index){     //get array item
>         return array_[index];
>     }
>     
>     IntBag::IntBag (const IntBag& a){        //copy constructr
>       size=a.getSize();
>       for(int i=0; i<size; i++){
>         int val=a[i];
>         array_[i]=val;
>       }
>     }
>     
>     int IntBag::getSize()const{    //get the size of the array
>       return size;
>     }
>     
>     IntBag& IntBag::operator = (const IntBag& a){
>       for(int i= 0; i< a.getSize(); i++) {
>         array_[i]=a[i];
>       }
>     }

**


我的错误是: $ g++ intbag.cpp intbag.cpp:在复制构造函数“IntBag::IntBag(const IntBag&)”中: intbag.cpp:19:16:错误:将“const IntBag”作为“this”参数传递会丢弃限定符 [-fpermissive] 19 | int val=a[i]; | ^ intbag.cpp:12:5: 注意:调用‘int IntBag::operator’ 12 | int IntBag::operator[](int index){ //获取数组项 | ^~~~~~ intbag.cpp:在成员函数“IntBag& IntBag::operator=(const IntBag&)”中: intbag.cpp:30:18:错误:将“const IntBag”作为“this”参数传递会丢弃限定符 [-fpermissive] 30 |数组_[i]=a[i]; | ^ intbag.cpp:12:5: 注意:调用‘int IntBag::operator’ 12 | int IntBag::operator[](int index){ //获取数组项 | ^~~~~~ intbag.cpp:32:1:警告:函数中没有返回语句返回非 void [-Wreturn-type] 31 | } +++ |+ 返回 *this; 32 | } | ^


enter image description here

【问题讨论】:

  • 不要发布文字图片。而是复制文本。
  • 不要在 C++ 问题中使用 C 标签。

标签: c++ arrays error-handling compiler-errors


【解决方案1】:

如何在 c++ 中消除这个 fpermissive 错误?

不要在 const 值上调用非 const 限定的成员函数。在这种情况下,非 const 限定成员函数是下标运算符重载,而 const 值是赋值运算符重载的参数 const IntBag&amp; a

鉴于下标运算符重载不会修改对象的状态,也不会返回非 const 引用,因此没有必要不使用 const 限定。因此,一个简单的解决方案是声明下标运算符 const。

【讨论】:

  • 所以我将运算符声明为 const。现在我收到另一条错误消息:“/usr/lib/gcc/x86_64-pc-cygwin/10/../../../../x86_64-pc-cygwin/bin/ld: /usr/lib /gcc/x86_64-pc-cygwin/10/../../../../lib/libcygwin.a(libcmain.o):在函数main': /usr/src/debug/cygwin-3.1.7-1/winsup/cygwin/lib/libcmain.c:37: undefined reference to WinMain'/usr/src/debug/cygwin- 3.1.7-1/winsup/cygwin/lib/libcmain.c:37:(.text.startup+0x82):重定位被截断以适应:R_X86_64_PC32 针对未定义的符号 `WinMain' collect2:错误:ld 返回 1 个退出状态"