C++プログラムのファイル分割とテンプレートの使用方法

このQ&Aのポイント
  • C++プログラムのファイル分割について説明します。myheader.hに関数の宣言を、function.cppに関数の内容を記述し、main.cppで使用します。
  • テンプレートを使用してどの型でも使える関数を実装する方法について説明します。関数宣言や関数の内容をテンプレートに対応させましょう。
  • C++プログラムでファイルを分けることにより、プログラムの可読性や保守性を高めることができます。また、テンプレートを使用することで汎用性の高いコードを作成することができます。
回答を見る
  • ベストアンサー

プログラムのファイル分割。

現在C++を学んでいるものです。 ソースファイルの分割についての質問です。よろしくお願いします。 環境はVisual Studio 2005です。 ファイルを      myheader.h      main.cpp      function.cpp と分ける事を考えると、例えば単純な int max(int num1, int num2){ if(num1 > num2) return num1; else return num2; } という関数を考えた場合、 myheader.hには関数maxの宣言int max(int num1, int num2);を。 function.cppには上記の関数maxの内容を。 そしてmain.cppで関数maxを使用するといったように分割し、実行することまでは自分でできます。 ですが、上記の関数をテンプレートを使って、どの型でも使用可能にするには、myheader.h、function.cppにはどのように記述したらよいでしょうか? テンプレートを使った関数は普通ですが、 template <class T> T max(T num1, Tnum2){ if(num1 > num2) return num1; else return num2; } というように記述したいと考えています。 よろしくお願いします

質問者が選んだベストアンサー

  • ベストアンサー
回答No.2

> ヘッダーファイルには通常プログラムは記述しない templateは"例外"です。 使われた(呼ばれた)時に初めてtemplate引数が何であるかが 確定するので、function.cppだけを別個にコンパイルしておくことが できません。

seven_star
質問者

お礼

詳しく解説していただきありがとうございました。 今後のプログラム作成に大きく役立つ経験になりました。 再度、心からお礼を申し上げます。

その他の回答 (1)

回答No.1

myheader.h に"ぜんぶ"書き、function.cppは不要。

seven_star
質問者

お礼

返答ありがとうございました。 確かに、myheader.hに全てを記述することが最短の解決策だと思います。 ですが、私は今大学生のため仕事で本格的にプログラムを組んだことは無いのですが、ヘッダーファイルには通常プログラムは記述しないということをこの”教えてgoo”の書き込みで読んだことがあります。 それは、管理が困難になるからという理由で、宣言またはグローバル変数の定義を行うことが普通であると記述されていました。 そのため、ヘッダーファイルには記述しないようにプログラムを組む練習を行おうと考えたのですが、やはり難しいですね^^

関連するQ&A

  • 分割コンパイルの手順と方法について

    Visual Studio 2010でファイルを分割してコンパイル、リンクする方法がわかりません。以下のような3つのファイルです。 [myfunc.h] /* max関数の宣言 */ int max(int x, int y); [myfunc.c] int max(int x, int y) { if (x > y) return x; else return y; } [Sample13.c] #include <stdio.h> #include "myfunc.h" int main(void) { int num1, num2, ans; printf("1番目の整数を入力してください。\n"); scanf("%d", &num1); printf("2番目の整数を入力してください。\n"); scanf("%d", &num2); ans = max(num1, num2); printf("最大値は%dです。\n", ans); return 0; } 以上3つのファイルはあくまでも便宜的なもので、複数のファイルのコンパイル・リンクの手順を具台的に理解するために 用意したものです。

  • C言語 関数の問題

    C言語(関数の問題)で読み込んだ4つの整数の最大値を求めプログラムで 整数を2つペア比較し、関数の入れ子を用いて最大値を見つけて、表示する。 というプログラムを作成したいのですが #include<stdio.h> int maxof(int a, int b) { if(a > b) return (a); else return (b); } int max4(int a, int b, int c, int d) { max(max(a, b), max(c, d)); } int main(void) { int num1,num2, num3, num4; ------ 整数の読み込み printf("最大値は%dです。", max4(num1, num2, num3, num4)); return(0); } と記述すると、上手くいったのですが これを max関数だけを用いて作成できますでしょうか? 整数の比較は全てmax関数で行いたいです。

  • ファイル分割について

    今本をみながら練習中なのですが、ファイル分割がうまくいきません。以下のような3つのプログラムをかいたのですが実行できません。 (一つ目:myfunc.h) int max(int x,int y); (二つ目:myfunc.c) int max(int x,int y){ if(x > y) return x; else return y;} (三つ目:sample.c) #include <stdio.h> #include "myfunc.h" int main(void){ int x,y,c; printf("1番目の整数\n"); scanf("%d",&x); printf("2番目の整数\n"); scanf("%d",&y); c = max(x,y); printf("最大値は%d\n",c); return 0;} すべてコンパイルしてsample.cを実行してもだめでした。ご指導お願いします><

  • linuxでリンクを貼るには

    linuxでリンクを貼るには 本に書いてある通りにプログラムをつくったのですが、 うまくコンパイルできません。 本で書いてあるのはwindowsのvisual C++で、 僕の使っている環境はlinuxのg++です。 コンパイルした結果を以下に示します。 -- ファイル名:myfunc.h //declaration of the max function int max(int x, int y); -- ファイル名:myfunc.cpp //a definition of the max function int max(int x, int y) { if(x > y) return x; else return y; } -- ファイル名:sample10.5.cpp #include <iostream> #include "myfunc.h" using namespace std; int main() { int num1, num2, ans; cout << "Please input the 1st integer.\n"; cin >> num1; cout << "Please input the 2nd integer.\n"; cin >> num2; ans = max(num1, num2); cout << "The maximum value is " << ans << '\n'; return 0; } -- bash-2.05b$ g++ myfunc.cpp /usr/lib/gcc-lib/i386-redhat-linux/3.2.3/../../../crt1.o(.text+0x18): In function `_start': : undefined reference to `main' collect2: ld はステータス 1 で終了しました -- bash-2.05b$ g++ sample10.5.cpp /tmp/ccWJNOkX.o(.text+0x6c): In function `main': : undefined reference to `max(int, int)' collect2: ld はステータス 1 で終了しました

  • C++のプログラムについて教えてください。

    C++のプログラムについて教えてください。 以下のようなプログラムでコンパイルを行うと、エラーが起きてしまい、原因が分かりません。 OSはMac OS X 10.6.4です。 プログラム //************************************ //main.cpp #include <iostream> class test{ private: static int num; public: test(); int get_num(); }; test::test(){ num=0; } int test::get_num(){ return num; } int main(){ test t; int num = t.get_num(); std::cout<<num<<std::endl; return (0); } //*********************************** g++ -o main main.cppでコンパイルした結果 Undefined symbols: "test::num", referenced from: test::test() in ccYWvIdB.o test::test() in ccYWvIdB.o test::get_num() in ccYWvIdB.o ld: symbol(s) not found collect2: ld returned 1 exit status のようにエラーが起きます。 どなたか分かる方がいればお願いします。

  • 外部ファイルでのtemplate関数の実装方法

    外部ファイルでのtemplate関数の実装方法 sub.cppにtemplate関数を実装し、 main.cppで、sub.cppのtemplate関数を呼び出す、 みたいなことをやりたいのですが、 コンパイルは通りますが、リンクエラー?になってしまいます。 以下が上記のサンプルプログラムです。 //main.cpp #include <vector> #include <iostream> using namespace std; template <typename t_ret, typename t_array> t_ret sub_t(const t_array&); int main (int argc, char *argv[]) { vector<double> v; v.push_back(1.1); v.push_back(2.2); cout << sub_t<double, vector<double> >(v) << endl; return 0; } // sub.cpp #include <vector> using namespace std; template <typename t_ret, typename t_array> t_ret sub_t(const t_array& array) { return array[0]+array[1]; } //コンパイルログ main.o: In function `main': main.cpp:(.text+0x134): undefined reference to `double sub_t<double, std::vector<double, std::allocator<double> > >(std::vector<double, std::allocator<double> > const&)' collect2: ld returned 1 exit status make: *** [main] Error 1 どなたか、対処方法を教えてください。 宜しくお願いします。

  • このプログラム見てください

    これで動いたと書いてあるのに動きません。 どこを直せば良いのか教えてください。 #include <stdio.h> int combination(int n,int r){ if ( r==0 ){ return 1; }else if( r==n ){ return 1; }else{ return (combination(n-1,r-1)+combination(n-1,r)); } } int main(){ int num_n=0; int num_r=0; int answer=0; printf("組み合わせの計算をします。数値を入力してください。N=?。\n"); printf("[n]:"); scanf("%d",&num_n); rewind(stdin); printf("[r]:"); scanf("%d",&num_r); rewind(stdin); answer=combination(num_n,num_r); printf("%dC%d=%d\n" , num_n, num_r, answer); return 0; }

  • 分割コンパイルについて

    現在分割コンパイルが分からずに苦戦しています。 下記のリストは構造体を使わなければコンパイラを通すことができましたが、 使うとなぜか通りません。 あれこれ試しましたがどうしても分かりません。 何がおかしいのでしょうか? *define.hで全てのファイルへの定義や宣言を行わせています。 ////////////// //Main.cpp ////////////// #include <stdio.h> #include <conio.h> #include "define.h" int main( void ){ Tmp[0].c = 15; printf("a: %d\n", a); printf("b: %d\n", b); printf("c: %d\n", Tmp[0].c); printf("NUM:%d\n", NUM); aaa(); bbb(); getch(); return 0; } ////////////////// // A.cpp ///////////////// #include <stdio.h> #include "define.h" void aaa( void ){ printf("a: %d\n", a); printf("b: %d\n", b); printf("c: %d\n", Tmp[0].c); printf("NUM:%d\n", NUM); } ////////////////// // B.cpp ///////////////// #include <stdio.h> #include "define.h" void bbb( void ){ printf("a: %d\n", a); printf("b: %d\n", b); printf("c: %d\n", Tmp[0].c); printf("NUM:%d\n", NUM); } ////////////////// // define.cpp ///////////////// #include "define.h" int a = 10; int b = 20; struct Parameter { int c; }; struct Parameter Tmp[NUM]; ////////////////// // define.h ///////////////// #define NUM 100 extern int a; extern int b; extern struct Parameter Tmp[NUM]; void aaa( void ); void bbb( void );

  • C++のファイル分割でのエラーについて

    最近VC2008でC++の勉強を始めたのですが、ファイル分割でLNK2005エラーというのが発生し、解消できません。 インクルードガードは行ったのですが、どうしたらよいのか分かりません。 ソースコードはこんな感じです。 //main.cpp #include "sub.h" #include "res.h" bool main(){ calcx(m_x); calcy(m_y); } //res.h 共有変数の宣言 #ifndef __RES_H #define __RES_H int m_x; int m_y; #endif //sub.h 関数のプロトタイプ宣言を行う void calcx(); void calcy(); //sub.cpp 関数の定義を記述する #include "res.h" void calcx(int x){ m_x = x + 100; } void calcy(int y){ m_y = y + 200; } エラー: 1>Main.obj : error LNK2005: "int m_x" (?m_x@@3HA) は既に sub.obj で定義されています。 1>Main.obj : error LNK2005: "int m_y" (?m_y@@3HA) は既に sub.obj で定義されています。 上記のようなエラーを解消するにはどうしたら良いのでしょうか。 何がおかしいのか指摘をお願いします。

  • インライン関数の使い道と理屈

    #include <iostream> using namespace std; //max関数の定義 inline int max(int x, int y){if(x>y) return x; else return y;} int main(){ int num1, num2, ans; cout << "1番目の整数を入力して下さい。\n"; cin >> num1; cout <<"2番目の整数を入力して下さい。\n"; cin >> num2; ans = max(num1, num2); cout << "最大値は" << ans << "です。\n"; return 0; } インライン関数の処理は呼び出し部分に埋め込まれるので、プログラムの処理速度が 向上することがありますとあるんですが、 どのような時にインライン関数は使用するのでしょうか? 理由もしくみもご教示お願いします。

専門家に質問してみよう