###前提・実現したいこと
現在、下記のコードのように、static変数を用意して、noを自動的にカウントアップしようとしています。
配列を用いた場合、コンストラクタが一回のみなので、カウントアップができません。
何か自動で繰り上げる方法はないでしょうか。
宜しくお願い致します。
###ソースコード
<メインクラス> #include <iostream> #include "string.h" #include "Worker.h" using namespace std; int Worker::no = 0; char* Worker::CompanyName = "ABC"; Worker::Worker(){ this->num; cout << "-------------------" << Worker::no << "\n"; this->salary = 0; strcpy(this->department, "NotDefinedDepartment"); strcpy(this->name, "NotDefinedName"); no++; } Worker::~Worker(){ } Worker::Worker(double salary ,char department[100], char name[100]){ this->num = no; this->salary = salary; strcpy(this->department,department); strcpy(this->name,name); no++; } void Worker::ShowData(){ cout << "no = " << this->no << "\n"; cout << "salary = " << this->salary << "\n"; cout << "department = " << this->department << "\n"; cout << "name = " << this->name << "\n"; } int main(void){ Worker w[3]; for(int i=0 ; i<3 ;i++){ w[i].salary = 100; strcpy(w[i].department, "E"); strcpy(w[i].name, "Takayuki"); } w[0].ShowData(); w[1].ShowData(); } <ヘッダークラス> #include <iostream> #include "string.h" #include "Worker.h" using namespace std; int Worker::no = 0; char* Worker::CompanyName = "ABC"; Worker::Worker(){ this->num; cout << "-------------------" << Worker::no << "\n"; this->salary = 0; strcpy(this->department, "NotDefinedDepartment"); strcpy(this->name, "NotDefinedName"); no++; } Worker::~Worker(){ } Worker::Worker(double salary ,char department[100], char name[100]){ this->num = no; this->salary = salary; strcpy(this->department,department); strcpy(this->name,name); no++; } void Worker::ShowData(){ cout << "no = " << this->no << "\n"; cout << "salary = " << this->salary << "\n"; cout << "department = " << this->department << "\n"; cout << "name = " << this->name << "\n"; } int main(void){ Worker w[3]; for(int i=0 ; i<3 ;i++){ w[i].salary = 100; strcpy(w[i].department, "E"); strcpy(w[i].name, "Takayuki"); } w[0].ShowData(); w[1].ShowData(); }
###補足情報(言語/FW/ツール等のバージョンなど)
paiza.io
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2016/01/20 00:42