c++中的const参数和const方法
const parameter and const method in c++
我有一个这样的类:
class MyClass
{
const int GetValue()
{
return 2;
}
}
我把它传递给一个类似这样的函数:
void Test(const MyClass &myClass)
{
int x=myClass.GetValue();
}
但我得到了这个错误:
The object has type qualifiers that are not compatible with member function Object type is const MyClass
我知道如果我这样定义函数:
void Test( MyClass &myClass)
但我想知道为什么添加const会产生这样的错误?
您需要使成员函数const
,而不是返回类型:
int GetValue() const;
这使得可以在const
实例上(或通过const
引用或指针)调用此成员。
注意:当你按值返回时,你返回的东西的常量与返回它的对象的常量是解耦的。事实上,你不太可能希望返回类型是const
。
您将int设置为const,尝试使方法const如下:
const int GetValue() const
{
return 2;
}
有两个问题,一个是可见性问题(您的const int GetValue()
函数由于私有而不可见),另一个是您正在调用一个非常量函数(它可以对将其作为成员函数的对象执行修改)
const int GetValue()
从一个常量引用到类
const MyClass &myClass
你基本上是在要求"这个对象不应该被修改,无论如何,让我调用一个不能保证这一点的函数"。
你不够连贯。
相关文章:
- 从 const 对象访问非 const 方法
- 为什么我可以调用一个从const方法更改成员的方法
- 使用新的c++返回值语法的Const方法
- const_cast const 方法中的"this"将"this"分配给外部变量?
- const 方法使用引用修改对象
- 从具有相同基数的另一个派生类调用派生类的非 const 方法
- 返回非常量引用编译的 Const 方法
- C++:无法从 const 方法返回对象的shared_ptr
- 是否可以从 const 方法迭代链表
- 为什么在const和非const方法中删除代码重复不是不确定的行为
- 在使用指向 const 和非 const 方法的成员指针时减少模板专用化的数量
- "可变"变量只能由 const 方法之一可变?
- Golang中的const方法
- C++ 逻辑恒常性和 const方法的按值返回
- c++将标志添加到const方法中
- C++防止const方法通过成员指针或引用更改数据
- 为什么 const 方法不覆盖 C++ 中的非 const 方法?
- 如何在const方法中迭代映射
- 为什么没有标准化的方法来避免const方法的代码重复
- 修改 const 方法中的 pointee 值