c++成员函数可以将this传递给普通函数

#include <iostream>
using namespace std;
class C; // 必须先申明C
void print(C* c); // 必须在C的定义之前声明print
class C
{
public:
	int a;
	C(int x) : a(x) {};
	void call() { print(this); }
};

void print(C* t)
{
	cout << t->a << endl;
}
int main() {
	/*初始化信号量,初始值为2,表示有两个顾客可以同时接收服务 */
	C c(1);
	c.call();
	return 0;
}

this指针是可以被delete的,delete之后可以访问成员方法,但是不能访问成员变量和虚函数。。

#include <iostream>
using namespace std;
class Test
{
public:
	Test(int _x);
	void foo();
	void show();
	void show(int);
private:
	int x;
};

Test::Test(int _x) :x(_x)
{
}

void Test::show()
{
	cout << "x = " << x << endl;
}

void Test::show(int)
{
	cout << "this is show int" << endl;
}

void Test::foo()
{
	delete this;
}

int main()
{
	Test *t1 = new Test(5);
	cout << "before" << endl;
	t1->show();
	t1->foo();
	cout << "after" << endl;
	//t1->show();
	t1->show(1);
	system("pause");
	return 0;
}

结果是可以打印出来的。。

但是访问成员变量会出错

before
x = 5
after
x = -572662307
请按任意键继续. . .

也不能访问虚函数(编译不能通过)

发布了81 篇原创文章 · 获赞 4 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/m0_37313888/article/details/105177965