[C ++] const member functions

const (regular) member function is a member function of the acquired object state, and can not change the state of the object (i.e. not modify the value of the object member). Declarations and definitions are as follows:

class A
{
public:
	void func() const;
};

A::void func() const
{
	// 常成员函数
}

One problem: If there are two functions of the same name, only one of which is often a member function, such wording is wrong?

class A
{
public:
	void func();
	void func() const;
};

The compiler and not being given!

Second problem: the parameter list should be the same, when called, the computer how to know which one is the transfer function?

class A
{
public:
    void func() { cout << "func()" << endl; };
    void func() const { cout << "func() const" << endl; };
};

int main()
{
	A a1;
	const A a2;

	a1.func();
	a2.func();
}

Output:
FUNC ()
FUNC () const

Description const对象才能调用const成员函数!

To clarify this issue, we must first understand how different objects that share the same member functions. Let us talk about const member functions to ordinary members function as an example:

int main()
{
	A a1;
	A a2;

	a1.func();
	a2.func();
}

When a1 and a2 are calling the member function, func () is how to distinguish the two objects do?

In fact, the member functions have a hidden parameter - this指针! That is, the compiler processes of member function is actually this:

class A
{
public:
	void func(A *this);
};

A::void func(A *this)
{
	// this指针
}

In this way, we will be able to distinguish which object to call a member function. We look back to this issue, it is clear, in fact, the compiler processes as follows:

class A
{
public:
	void func(A *this);
	void func(const A *this);	// const成员函数
};

Obviously, these two functions 互为重载! Overloaded function of course of the same name, and a2 const object passed this pointer is const pointer to call const member functions.

Published 15 original articles · won praise 1 · views 1663

Guess you like

Origin blog.csdn.net/weixin_43465579/article/details/99705234