C++定义类对象注意事项

#include <iostream>
using namespace std;

class background_task
{
public:
	background_task()
	{
		cout << "默认构造" << this->m_num << endl;
	}
	background_task(int num)
	{
		this->m_num = num;
		cout << "带参构造" << this->m_num << endl;
	}
	//void operator()()
	//{
	//	cout << "background_task.....operator..." << endl;
	//}

private:
	int m_num = 20;
};

int main()
{
	background_task b1;		//1
	background_task b2();	//2
	background_task b3(10); //3

	// 无区别
	background_task *p1 = new background_task;
	background_task *p2 = new background_task();

	//对于内置类型而言,加括号是进行了初始化,不加是未进行初始化
	int *p1Int = new int();
	int *p2Int = new int;


	//b1();

	background_task();	  //匿名对象
	background_task(199); //匿名对象
	background_task bts1 = background_task();	// 同background_task b1;
	background_task bts2 = background_task(10);// 同background_task b3(10);;
	return 0;
}

分析上述定义声明变量三种的区别:

1、定义局部变量b1,自动调用类background_task的不带参构造函数。

2、特别注意:此处相当于声明了一个函数 返回值是background_task 函数名b2 只是声明 ,未实现。

3、定义局部变量b3,自动调用类background_task的带参构造函数

Note:

在代码中注释的部分需要特别注意::

此时b1()    是调用了函数符重载函数  void operator()()

有时候我们传给函数参数时使用匿名对象,但有时与期望不同:

#include <iostream>
#include <thread>
using namespace std;

class background_task
{
public:
	background_task()
	{
		cout << "默认构造" << this->m_num << endl;
	}
	background_task(int num)
	{
		this->m_num = num;
		cout << "带参构造" << this->m_num << endl;
	}

	void operator()()
	{

		cout << "background_task...Threadid:" << this_thread::get_id() << endl;
		cout << "Threadnum:" << this->m_num << endl;
	}

private:
	int m_num = 20;
};

int main()
{
	//那么此时编译器会把background_task()解释为函数声明background_task (__cdecl *)(void)
	//std::thread   t(background_task()); 

	// 解决上述问题两种方案
	std::thread   t1((background_task()));
	std::thread   t2{background_task(100)};

	int numA = 2000;
	std::thread  t3([&](){
		cout << "lambda" << numA << endl;
		numA = 1000;
	});

	
	t1.join();
	t2.join();
	t3.join();
	cout << "main numA=" << numA;
	return 0;
}
发布了343 篇原创文章 · 获赞 57 · 访问量 20万+

猜你喜欢

转载自blog.csdn.net/jadeshu/article/details/103543692