#include <iostream> #include <cstring> using namespace std; // structを使用してクラス型を定義する struct st_type { st_type(double b, const char *n); void show(); private: double balance; char name[40]; }; st_type::st_type(double b, const char *n) { balance = b; strcpy(name, n); } void st_type::show() { cout << "名前: " << name; cout << ": $" << balance; if (balance < 0.0) cout << "***"; cout << "\n"; } int main() { st_type acc1(100.12, "Johnson"); st_type acc2(-12.34, "Hedricks"); acc1.show(); acc2.show(); return 0; }
$ g++ sample10.cpp $ ./a.out 名前: Johnson: $100.12 名前: Hedricks: $-12.34***
上のコードの構造体struct部分をクラスclassに変更すると以下のコードになる。
#include <iostream> #include <cstring> using namespace std; struct cl_type { double balance; char name[40]; public: cl_type(double b, const char *n); void show(); }; cl_type::cl_type(double b, const char *n) { balance = b; strcpy(name, n); } void cl_type::show() { cout << "名前: " << name; cout << ": $" << balance; if (balance < 0.0) cout << "***"; cout << "\n"; } int main() { cl_type acc1(100.12, "Johnson"); cl_type acc2(-12.34, "Hedricks"); acc1.show(); acc2.show(); return 0; }
$ g++ sample11.cpp $ ./a.out 名前: Johnson: $100.12 名前: Hedricks: $-12.34***