Summary of several methods of calling member functions in C++

1. Object call

#include<iostream>
using namespace std;

class Person
{
public:
	void sayHello()
	{
		cout << "Hello!" << endl;
	}
};

int main()
{
	Person p;
	p.sayHello();//对象调用成员函数

	return 0;
}

2. Pointer call

#include<iostream>
using namespace std;

class Person
{
public:
	void sayHello()
	{
		cout << "Hello" << endl;
	}
};

int main()
{
	Person* p = new Person();//new操作符在堆上动态分配了一个内存空间来存储一个Person对象,
	//然后调用默认的构造函数Person()来初始化这个Person对象,然后返回一个指向该对象的指针
	p->sayHello();

	delete p;//释放p所指向的动态分配的内存空间,而不是释放p本身

	return 0;
}

3. Call by reference

#include<iostream>
using namespace std;

class Person
{
public:
	void sayHello()
	{
		cout << "Hello" << endl;
	}
};

int main()
{
	Person& p = *(new Person());//使用new关键字在运行的时候动态分配内存为Person类型,
	//然后用指针、解引用、引用操作来创建该类型的引用p
	// 记住:&用在对象前面时只有引用的作用,就会创建一个指向该对象的别名
	// &在声明引用的时候不是在内存中创建一个新的对象,而是创建该对象的一个新的别名
	// &声明一个指向Person对象的引用,这个引用被命名为P,
	// 该引用的类型是"Person&",而不是"Person*"
	// 这个p是引用,不是对象;p也是指向这个对象的一个指针
	//new Person()在堆区分配一个新的对象
	//*(new Person())返回一个Person对象详
	p.sayHello();//引用调用
	delete &p;//delete时需要传递该指针指向的地址,用&p就可以获得指针所指向内存的地址,
	//而不是传递指针p本身


	return 0;
}

4. Call other member functions through this pointer in the member function

#include<iostream>
using namespace std;

class Person
{
public:
	void sayHello()
	{
		cout << "Hello!" << endl;
		this->sayWorld();//this指针的对象是当前调用成员函数的对象,即this指向的是p;
		//等价于直接调用sayHello();
	}

	void sayWorld()
	{
		cout << "World" << endl;
	}
};

int main()
{
	Person p;
	p.sayHello();


	return 0;

5. Call the static member function through the class name and scope operator in the member function

#include<iostream>
using namespace std;

class Myclass
{
public:
	static int staticFunc(int x)
	{
		return x * x;
	}

	//在成员函数内通过类名和::访问成员函数
	

	//int r = Myclass::staticFunc(int x);错误
	//不能在函数内定义成员函数的时候,不能直接调用类的其他成员函数进行初始化
	//函数体内的代码是在对象被实例化后才会被执行的,而类的成员函数或者成员变量
    //的初始化化是在对象的
	//构造函数中进行的.如果在函数体内直接调用其他成员函数进行初始化,那么这个被
    //调用的成员函数可能还没被初始化,从而报错

	//改正1
	/*Myclass(int x)
	{
		int result = Myclass::staticFunc(x);
	}*/

	//改正2
	int nonStaticFunc(int x)
	{
		int result = Myclass::staticFunc(x);
		return result;
	}
	//在类的成员函数内通过类名和::来访问其他成员函数时可以的,
    //因为类的成员函数通过this指针
	//访问类的成员变量和其他成员函数
	//在类的成员函数内部,this指针指向当前对象实例的地址,
    //所以可以通过this指针来访问类的成员函数和变量,及时这些成员函数还没有被初始化
};

int main()
{
	Myclass p;
	int result=p.nonStaticFunc(5);
	cout << "result = " << result << endl;


	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_53328532/article/details/130033496