#include <iostream> using namespace std; class A{ private: int num; public: A(int num){ this->num = num; } void printA(){ cout<<"A "<<num<<endl; } }; template <class T> class demostrate{ public: demostrate(T* pObj = 0){ cout<<"default constructor"<<endl; }; demostrate(const demostrate &demo){ cout<<"copy constructor"; } //demostrate(demostrate<T> demo){}; demostrate& operator=(T *t); }; template <class T> demostrate<T>& demostrate<T>::operator=(T *t){ cout<<"operator overload"<<endl; t->printA(); return *this; } class B{ public: B(A* a){ a->printA(); cout<<"new A "<<endl; } B(int bint){ cout<<"bint "<<bint<<endl; } B(int a, int b, int c){ cout<<"output a,b,c "<<a<<b<<c<<endl; } }; int main(){ //第一种方法提示conversion from ‘A*’ to non-scalar type ‘demostrate<A>’ requested //带有声明的对象初始化,实际上是调用构造函数,所以构造函数一定要有demostrate(T* pObj = 0)形参列表 demostrate<A> demo = new A(100); /* //第二种方法调用的是运算符重载方法 demostrate<A> demo; demo = new A(100); B b= new A(200); B b2 = 300; B b3 = {100, 200, 300}; */ return 0; }
在C++中,为构造函数指定实参有三种等价形式:
Account acct1("Anna Press");
Account acct2 = Account("Anna Press");
Account acct3 = "Anna Press";
acct3的形式只能被用于指定单个实参的情形,对于两个以上的实参,只能使用acct1和acct2的形式,推荐acct1。