C++关于自动构造对象的隐式类型转换

关于C++的隐式类型转换有好几种,这篇博客解释一下其中的一种,就是当形参是对象时自动构造的一个例子。

学习时看到一道问答题,问的是请说一说隐式类型转换,看到其中的一个转换是这样的:对于只存在单个参数的构造函数对象构造来说,函数调用可以直接使用该参数传入,编译器会自动调用其构造函数生成临时对象。为了验证一下,写了个测试的demo,代码如下所示:

#include <iostream>
#include <math.h>

using namespace std;

class SayHello
{
public:
	SayHello(const char* p) 
	{ 
		cout << "Construct!" << endl;
		message = p; 
	}

	~SayHello()
	{
		cout << "Destruct!" << endl;
	}

	const char* message;
};

void printWord(SayHello the_object)
{
	cout << the_object.message << endl;
}

int main()
{
	printWord("Hello world!");

	return 0;
}

这里要注意一下,一定要是单个参数的构造,才能进行隐式类型转换!

执行结果如下所示:
在这里插入图片描述

发布了27 篇原创文章 · 获赞 9 · 访问量 2637

猜你喜欢

转载自blog.csdn.net/IcdKnight/article/details/104950715
今日推荐