C++の入門者で、template,classの使い方について学んでいます。
下記末尾に例示のcodingで、constructorを
//Constructor // This does not work right. Cal() :a(1), b(1) {}
とするとfloatに対応しないのでダメなようす。
それで、
//Constructor Cal(T pa, T pb) :a(pa),b(pb){} //This works good.
または
//Constructor Cal(T pa, T pb) { a = pa; b = pb;} //This works good too.
としてT型を明示して代数を代入すると良いことが分かりました。
しかし、この代数では実数でないので、initialize 出来ないのではないかと疑問がわきました。この場合は実数が入らなくても initialize 可能なのですか?
これはどう理解したらよいのかご案内お願いします。
//Sample coding: template <class T> class Cal { T a, b; public: Cal(T pa, T pb) :a(pa),b(pb){} //This works good. void get() { cout << "Type values of members." << endl; cin >> a >> b; } void cal_add() {cout << a << " + " << b <<" = "<< a+b << endl;} void cal_subtra() { cout << a << " - " << b << " = " << a - b << endl; } void cal_multi() { cout << a << "x " << b << " = " << a * b << endl; } void cal_div() { cout << a << " / " << b << " = " << a / b << endl; } }; int main() { int temp_a=1, temp_b=2; float temp_fa=1.1, temp_fb=2.2; Cal <int> int_test(temp_a, temp_b); Cal <float> flt_test(temp_fa, temp_fb); int_test.get(); int_test.cal_add(); int_test.cal_subtra(); int_test.cal_multi(); int_test.cal_div(); return 0; }
「この代数ではinitialize出来ないのではないか」とはどのような意味かわかりませんでした。もう少し具体的な事例をご提示いただけないでしょうか。
お世話になります。maisumakunさんが書いてくれたような内容です。Initializeするのに数字を入れないと出来ないのだ、と覚えてきたので、
Cal(T pa, T pb) { a = pa; b = pb;}
というようにaに代入して、なぜ不安定にならないのかが分かりませんでした。
回答2件
あなたの回答
tips
プレビュー