如何将const形参从一个成员函数传递到另一个成员函数

How to pass a const parameter from a member function into another member function?

本文关键字:函数 成员 一个 另一个 const 形参      更新时间:2023-10-16

我有一个class

 class Foo : Bar {
 public:
 virtual bool function1(const Card &arg1) const{
     function2(arg1);
 }
 virtual void function2(const Card &anotherArg) {
     /* Do stuff with private member variables*/
 }
 private:
 ....
 };

"Card"是一个类类型。我得到一个错误"成员变量函数'function2'不可用:'这个'参数有类型'const简单',但函数没有标记const。"

我不太确定是什么问题。Function2接受const作为参数之一,所以arg1是const应该不是问题,因为它不会被修改。另外,我试着这样做:

function2(arg1) const; 

但是它也不工作

在您的示例中,function1()const的方法。const方法只能调用其他const方法。function2()不是const方法。

这与每个方法的实际参数无关。

const this只能调用const this,非const this可以同时调用两者。在你的代码中,你用const this调用非const this:函数1的this是const,而函数2的this是非const,因此这是错误。

  • 函数2可以调用函数。

纠正你的例子:

class Foo : Bar 
{
     public:
         virtual bool function1(const Card &arg1) const
         {
             function2(&arg1);
         }
         virtual void function2(const Card &anotherArg)const
         {
             /* Do stuff with private member variables*/
         }
     private:
 ....
 };