use*_*263 -1 c++ oop scope pass-by-value
从有关const函数的MSDN页面
代码:
// constant_member_function.cpp
class Date
{
public:
Date( int mn, int dy, int yr );
int getMonth() const; // A read-only function
void setMonth( int mn ); // A write function; can't be const
private:
int month;
};
int Date::getMonth() const
{
return month; // Doesn't modify anything
}
void Date::setMonth( int mn )
{
month = mn; // Modifies data member
}
int main()
{
Date MyDate( 7, 4, 1998 );
const Date BirthDate( 1, 18, 1953 );
MyDate.setMonth( 4 ); // Okay
BirthDate.getMonth(); // Okay
BirthDate.setMonth( 4 ); // C2662 Error
}
Run Code Online (Sandbox Code Playgroud)
但是如何month在setMonth函数中进行修改?函数传递值并且不返回任何值.此外,如果没有传入,函数如何知道修改它的月变量?
此外,如果没有传入,函数如何知道修改它的月变量?
成员函数(如setMonth())隐式接收this指向Date它们被调用的类型对象(在本例中)的指针.对于限定为的成员函数const,this指针是指向的指针const,它不允许您修改指向对象的状态.
实际上,以下内容:
void Date::setMonth( int mn )
{
month = mn; // Modifies data member
}
Run Code Online (Sandbox Code Playgroud)
相当于以下内容:
void Date::setMonth( int mn )
{
this->month = mn; // Modifies data member
// ^^^^^^
// "this" is a pointer to an object of type Date (i.e. Date*),
// and that is the object on which setMonth() is invoked
}
Run Code Online (Sandbox Code Playgroud)
所有其他成员函数的故事相同,因此:
int Date::getMonth() const
{
return month; // Doesn't modify anything
}
Run Code Online (Sandbox Code Playgroud)
相当于:
int Date::getMonth() const
// ^^^^^ Means the implicit "this" pointer is const
{
return this->month; // Doesn't modify anything
// ^^^^^^
// Here, "this" is a pointer to a CONST Date object (i.e. Date const*),
// and that is the object on which getMonth() is invoked
}
Run Code Online (Sandbox Code Playgroud)
重要说明:隐式this指针实际上是指向const调用成员函数的对象是否具有const-qualified类型的指针.
这就是为什么你不能调用它本身不是一个成员函数const的对象,其类型上-qualified 是 const -qualified:一个状态 const 的对象不应该被改变,以及非const功能不承诺永远不会改变它.
因此,编译器将阻止您通过引发错误来调用非限定类型(例如)对象上的非const函数(例如Date::setMonth()).constconst Date