如何抑制构造函数的隐式转换?

首先看看何为构造函数的隐式转换,

#include <iostream>
using std::cout;
using std::endl;

class A
{
public:
	A()
	{
	    cout<<"constructor A"<<endl;
	}
};

class B
{
	public:
	B(A& a)
	{
		cout<<"constructor B"<<endl;
	}
};

void func(B b)
{
    cout<<"func";
}

int main()
{
	A a;
	func(a);

	return 0;
}

当调用func(a)时,会发生对象拷贝,此时会调用类B的拷贝构造函数B(A&),而如果我们并不希望这种转换发生,就可以在构造函数前加上explicit关键字,如果此时编译就会产生错误:

C:\Users\Study\share\TestCpp\test.cpp||In function `int main()':|
C:\Users\Study\share\TestCpp\test.cpp|31|error: conversion from `A' to non-scalar type `B' requested|
||=== Build finished: 1 errors, 0 warnings ===|
 

posted on 2012-05-07 14:46  IT技术畅销书  阅读(211)  评论(0)    收藏  举报

导航