// sample program ; ClassTemplate.cc 2004.8.22,2008.10.22 T. Kondo #include using namespace std; template class Array{ private: T data[3]; public: void setData(int n, T d); T getData(int number); }; template void Array::setData(int number, T d) { if(number <0 || number > 2) cout <<"input number is outside the allowed region" << endl; else data[number] = d; } template T Array::getData(int number) { if(number <0 || number > 2){ cout <<"input number is outside the allowed region" << endl; return data[0]; } else return data[number]; } class Car{ private: int* pN; protected: double gas; public: int Npublic ; // test public number Car(double g=100.0); //overloading with default argument ~Car(); // destructor void setGas(double data){gas=data;} // void showGas(); virtual void showGas(); }; int main() { cout << "create integer array" << endl; Array iArray; iArray.setData(0,123); iArray.setData(1,243); iArray.setData(2,524); for(int i=0; i<3; i++) cout << iArray.getData(i) << endl; cout << "create double floating array" << endl; Array dArray; dArray.setData(0,1.23); dArray.setData(1,2.43); dArray.setData(2,5.24); for(int i=0; i<3; i++) cout << dArray.getData(i) << endl; //-------Try Template with class Car--------------------------------------------- Car mycar; // define object "mycar" with constructor mycar.Npublic = 60; cout << "public number Car.Npublic =" << mycar.Npublic << endl; mycar.showGas(); // mycar.setGas(99.2); // set gas by 99.2 mycar.showGas(); Car mycar2(191.34); // use overloading constructor mycar2.showGas(); cout << "try Template"<< endl; Array CarArray; CarArray.setData(0,mycar); CarArray.getData(0).showGas(); CarArray.setData(1,mycar2); CarArray.getData(1).showGas(); return 0; } Car::Car(double g) // constructor with default argument { gas=g; } Car::~Car() { cout << " destructor"<< endl; } void Car::showGas() { cout << "gas =" << gas << " (called from base class)" << endl; } ------------------ClassTemplate.ccの実行結果は------------------------ create integer array 123 243 524 create double floating array 1.23 2.43 5.24 public number Car.Npublic =60 gas =100 (called from base class) gas =99.2 (called from base class) gas =191.34 (called from base class) try Template destructor gas =99.2 (called from base class) destructor destructor gas =191.34 (called from base class) destructor destructor destructor destructor destructor destructor