如何将const形参从一个成员函数传递到另一个成员函数
How to pass a const parameter from a member function into another member function?
我有一个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:
....
};
相关文章:
- 如何使用指针传递给函数的数组中对象的函数成员
- c++构造函数成员初始化:传递参数
- 创建 std::函数,它返回具有函数成员值的变量.分段错误
- 如何在C++通过公共函数访问私有函数成员?
- 解释了构造函数成员初始化列表
- 调用std::函数成员时内存损坏
- 是否可以为模板类的模板函数成员设置别名?
- 捕获 lambda 函数C++成员变量
- 构造函数成员初始值设定项跨成员列出,安全吗?
- 获取与在模板参数中传递的函数成员类型相同的类
- 如何从公共函数成员访问地图私有成员
- C 构造函数成员分配优化
- 使用命名空间进行函数成员定义
- 函数成员作为 CUDA 内核的参数
- 模板基类函数成员的别名
- 函数成员中用于void和继承的enable_if
- 头文件中是否定义了一个很长的Class函数成员
- 类内/构造函数成员初始化
- 使用指向部分专用函数成员的指针自动填充向量
- 指向函数成员的指针