C++语言99个常见编程错误 常见错误88:对模板化的复制操作的认识误区

常见错误88:对模板化的复制操作的认识误区


  对于模板成员函数的一个普通用途是用于实现构造函数。很多标准库中的容器组件都会有个
模板化的构造函数,这样就允许使用一个元素序列来初始化该容器:
  模板化的构造函数的运用使得容器能够接受任意类型的输入序列,若非如此,容器类型之
实用性也就大打折扣。而标准库中的auto_ptr模板组件亦使用模板成员函数:

  模板成员函数绝不会为完成赋值操作而实例化。


money.h
#ifndef MONEY_H
#define MONEY_H

enum Currency { CAD, DM, USD, Yen };

class Curve {
  public:
	Curve( Currency )
		{}
	double convert( Currency, Currency, double amt ) const
		{ return amt; }
};

template 
class Money {
  public:
    Money( double amt );
    template 
        Money( const Money & );
    template 
        Money &operator =( const Money & );
    ~Money();
    double get_amount() const
    	{ return amt_; }
    //...
  private:
    Curve *myCurve_;
	double amt_;
};


template 
Money::Money( double amt )
	: myCurve_( new Curve(currency) ), amt_(amt) {}

template 
Money::~Money()
	{ delete myCurve_; }

template 
template 
Money::Money( const Money &that )
	: myCurve_( new Curve(currency) ), amt_(myCurve_->convert(currency,otherCurrency,that.get_amount())) {}

template 
template 
Money &Money::operator =( const Money &rhs ) {
	amt_ = myCurve_->convert( currency, otherCurrency, rhs.get_amount() );
	return *this;
}

#endif

money.cpp
无内容

main.cpp
#include "money.h"
#include
int main() {
	Money acct1( 1000000.00 );
	Money acct2( 123.45 );
	Money acct3( acct2 ); // template ctor
	Money acct4( acct1 ); // compiler-generated copy ctor!
	acct3 = acct2; // template assignment
	acct4 = acct1; // compiler-generated assignment!
	getchar();
	return 0;
}


输出
无输出

你可能感兴趣的:(c++)