C++可以被重載的copy constructor函數--template copy constructor

Adam posted @ Sat, 17 Nov 2012 16:37:10 +0800 in C++ , 1792 readers

前天晚上幫大家複習C+_+,當時在講函數重載的時候羊說錯了一點。那就是Copy Constructor其實是可以重載的。

當時緣起是一道考試題,然後就忘了怎麼講到這個的。那時候我還在想這個問題,不過我還是這麼告訴別人了。今天再想了一會兒,覺得不妥,然後查閱了一番,發現Copy Constructor也是可以重載的。

在運用template的時候,我們有時候是需要在“複製一個對象”的時候,完成一次“隱式類型轉換”,這時候就要用到template copy constructor了。比如說,你可能在有時候需要將int拷貝出一份double型的數據,或者使用C-字符串char *類型的字符串轉換成一個C++ std::string類型的字符串等等。

舉例如下:

#include <cstdio>

template <typename T>
class Test
{
public:
	Test() {
		fprintf(stdout, "Here in Constructor ");
		fprintf(stdout, "%p\n", this);
	}// default constructor
	
	Test(const Test<T> & rhs) {
		fprintf(stdout, "Here in copy constructor - standard version ");
		fprintf(stdout, "%p cp from %p\n", this, &rhs);
	}// copy constructor
	
	template <typename AnotherType>
	Test(const Test<AnotherType> & rhs) {
		fprintf(stdout, "Here in copy constructor - template version ");
		fprintf(stdout, "%p cp from %p\n", this, &rhs);
	}// template copy constructor

	~Test() {}
};// class Test

int main()
{
	Test<int> t1;
	Test<int> t2(t1);
	Test<double> t3(t1);

	return 0;
}//main

運行結果爲:

 

Here in Constructor 0x7fff9d64a808
Here in copy constructor - standard version 0x7fff9d64a800 cp from 0x7fff9d64a808
Here in copy constructor - template version 0x7fff9d64a7f0 cp from 0x7fff9d64a808

 

  • No match
  • No match

Login *


loading captcha image...
(type the code from the image)
or Ctrl+Enter