在 C++ 中调用带或不带 "const" 签名的函数
Calling functions with or without "const" signature in C++
#include <iostream>
using namespace std;
class Object
{
public:
Object() {}
void Print() const
{
cout << "const" << endl;
}
void Print()
{
cout << "mutable" << endl;
}
};
void print_obj(const Object& obj)
{
obj.Print();
}
int main()
{
Object obj1;
const Object obj2;
Object*const pobj1 = &obj1;
print_obj(obj1);
print_obj(obj2);
obj1.Print();
obj2.Print();
pobj1->Print();
return 0;
}
我知道输出是
const
const
mutable
const
mutable
我想对于 const 对象,它会查找 const 函数。否则可变函数。但为什么最后一个是可变的?
But why is the last one mutable?
Object*const pobj1 = &obj1;
声明 pobj1
为指向非 const
对象的 const
指针。该对象仍然是可变的,但指针不是。
变量初始化后,您将无法将其更改为指向另一个变量。
pobj1 = &obj2; // Not OK.
但是你仍然可以改变它指向的变量,通过指针调用class的非const
成员函数
*pobj1 = obj2; // OK
But why is the last one mutable?
这是因为声明是Object* const pobj1
。由于我们使用的是指针,因此有 2 种 const 可能性。
const Object* const pobj1 OR Object const * const pobj1
^^1^^ ^^2^^ ^^1^^ ^^2^^
// 1 applies to the types (i.e., Object)
// 2, which is what you're using applies to the pointer, therefore you're using a non-const Object
我相信你的意思是 "const Object*"。 "const" 可以应用于指针 and/or 指针指向的对象。不同之处在于 "Object * const" 与 "Object const*".
相同
这个
Object*const pobj1 = &obj1;
将 pobj1 声明为指向非常量对象的常量指针。如果你怀疑,
只需将其更改为
Object*const pobj2 = &obj2;
这不会编译,因为它丢弃了 obj2 的 const 限定符。
顺便说一句,限制是对于 const 对象,它只能使用 const 函数。括号后的 'const' 表示 'this*' 指针将被视为指向方法内 const 对象的指针。
对于非const对象,它可以同时使用const和non-const方法,但它会选择首先使用non-const(如果两者都被定义)。
#include <iostream>
using namespace std;
class Object
{
public:
Object() {}
void Print() const
{
cout << "const" << endl;
}
void Print()
{
cout << "mutable" << endl;
}
};
void print_obj(const Object& obj)
{
obj.Print();
}
int main()
{
Object obj1;
const Object obj2;
Object*const pobj1 = &obj1;
print_obj(obj1);
print_obj(obj2);
obj1.Print();
obj2.Print();
pobj1->Print();
return 0;
}
我知道输出是
const
const
mutable
const
mutable
我想对于 const 对象,它会查找 const 函数。否则可变函数。但为什么最后一个是可变的?
But why is the last one mutable?
Object*const pobj1 = &obj1;
声明 pobj1
为指向非 const
对象的 const
指针。该对象仍然是可变的,但指针不是。
变量初始化后,您将无法将其更改为指向另一个变量。
pobj1 = &obj2; // Not OK.
但是你仍然可以改变它指向的变量,通过指针调用class的非const
成员函数
*pobj1 = obj2; // OK
But why is the last one mutable?
这是因为声明是Object* const pobj1
。由于我们使用的是指针,因此有 2 种 const 可能性。
const Object* const pobj1 OR Object const * const pobj1
^^1^^ ^^2^^ ^^1^^ ^^2^^
// 1 applies to the types (i.e., Object)
// 2, which is what you're using applies to the pointer, therefore you're using a non-const Object
我相信你的意思是 "const Object*"。 "const" 可以应用于指针 and/or 指针指向的对象。不同之处在于 "Object * const" 与 "Object const*".
相同这个
Object*const pobj1 = &obj1;
将 pobj1 声明为指向非常量对象的常量指针。如果你怀疑, 只需将其更改为
Object*const pobj2 = &obj2;
这不会编译,因为它丢弃了 obj2 的 const 限定符。
顺便说一句,限制是对于 const 对象,它只能使用 const 函数。括号后的 'const' 表示 'this*' 指针将被视为指向方法内 const 对象的指针。
对于非const对象,它可以同时使用const和non-const方法,但它会选择首先使用non-const(如果两者都被定义)。