• 締切済み

c++ クラスに関してです。

うまくクラス同士を連動させることができなくてエラーが出てしまいます。 どこが間違えているのかアドバイスくださると助かります。 #ifndef H22_H_ #define H22_H_ #include <string> #include "account.h" class Bank { public: Bank(); void deposit(double amount, const std::string& accountType); void withdraw(double amount, const std::string& accountType); void transfer(double amount, const std::string& accountType); double getBalance() const; double getSavingsBalance() const; double getCheckingBalance() const; private: Account checking, savings; }; #endif #ifndef ACCOUNT_H #define ACCOUNT_H #include <string> #include "account.h" class Account{ public: Account(); Account(double &amout); double deposit(double amount); double getBalance() const; double withdraw(double amount); double balance; private: }; #endif #include <iostream> #include "acount.h" using namespace std; Account::Account { balance = 0; } Account::Account(double amount) { balance = amount; } Account::double deposit() const { return balance; } Account::double getBalance(double balance) { balance += amount; return balance; } Account::double withdraw(double amount) { if(amount > balance) { balance -= 5; return balance; } elese { balance -= amount; return balance; }} h22.h の中身 #include <string> #include "h22.h" #include "account.h" #include <stdexcept> using namespace std; Bank::Bank() { Account checking; Account saving; } void Bank::deposit(double amount, const string& accountType) { if (accountType != "S" && accountType != "C") throw invalid_argument("Does not compute"); else if(accountType == "S") savings.balance += amount; else if(accountType == "C") checking.balance += amount; } void Bank::withdraw(double amount, const string& accountType) { if (accountType != "S" && accountType != "C") throw invalid_argument("Does not compute"); else if(accountType == "S") savings.balance -= amount; else if(accountType == "C") checking.balance -= amount; } void Bank::transfer(double amount, const string& accountType) { if (accountType != "S" && accountType != "C") { throw invalid_argument("Does not compute");} else if(accountType == "S") { savings.balance += checking.balance; savings.balance = 0;} else if(accountType == "C") { checking.balance += amount; checking.balance = 0;} } double Bank::getBalance() const { return getBalance(); } double Bank::getSavingsBalance() const { return savings.getBalance(); } double Bank::getCheckingBalance() const { return checking.getBalance(); } メイン.cpp http://pastebin.com/rQTj8xciです。 なにかヒントやアドバイスお願いします

  • kko00
  • お礼率0% (0/10)

みんなの回答

回答No.3

初心者だと質問の仕方も分からなくて難しい所も多いかとは思いますが、初めに文句を述べさせて頂きます (わざと厳しく書いている所があるという事は御承知下さい)。 他の方も仰っている様に、質問文のコードを見るとまともにコンパイルが通らない様なコードです。とすれば、そもそも質問者さんの所でコンパイルが通っていないか、てもとのコードはコンパイルが通るが質問入力欄にコードを手で入力してミスっているかと思われるのですが…。前者ならば「連動させることができない」のではなくそれ以前の問題として「コンパイルが通らない」と書くべきだし、後者であるのならば実際のコードの内容を「コピー&ペースト」で貼り付けるべきです。 また、質問の仕方にも問題があるかと思います。コードを貼り付けるのではなく、何が目的で何が問題点になっているのかを説明するべきです。長いコードを貼り付けて単に問題点を教えてくれというのでは、回答する側も何を答えたらよいのやら分かりません。(問題点というのは目的によって変わりますよね。物凄く極端な例を言えば、もしコンパイルエラーを出す事が目的であれば、質問文のコードには問題点はないわけです。ちゃんとエラーを出す訳ですから(極端すぎるとは思いますが)。 あるいはもっと現実的な例として、いざコンパイルが通った後の動作が期待していた物と違うという場合には、期待していた動作が何かと実際にはどうなるかを説明しないと問題点は相手に伝わりません。) で、以降は質問者さんが遭遇しているのはコンパイルエラーだと仮定して話を進めます。ソースコードの内容的に、上から順に h22.h, account.h, account.cpp, h22.cpp という(感じの名前の)ファイルの中身を貼り付けた物と推測致します(ファイル名は重要なので書いて下さい)。 1h22.h: コンストラクタ Bank(double,double); がない。(main.cpp から呼ばれている) 2 account.h: #include "account.h" →不要。(自分自身を include している。もし include guard がなかったら無限ループになる所です。) 3 account.h: ×Account(double &amout) → ○Account(double amount) 4 account.cpp: #include "acount.h" の acount は account のスペルミス 5 account.cpp: ×Account::Account → ○Account::Account() 6 account.cpp: ×Account::double 関数名(...) → ○ double Account::関数名(...) (3箇所) 7 account.cpp: ×関数名の deposit と getBalance が逆 8 account.cpp: ×getBalance(double balance) → ○deposit(double amount)。引数名が間違っている 9 account.cpp: ×elese → ○ else 10 地の文: ×h22.h の中身→×h22.cpp の中身 11 h22.cpp: Bank::Bank() の中身 Account checking; → 不要 (Account checking は this->checking と何の関係もない。更に、this->checking は Account のデフォルトコンストラクタで初期化済み) 12 h22.cpp: Bank::Bank() の中身 Account savings; → 不要 (同上) 13 h22.cpp: Bank::Bank(double checking,double saving) がない。追加する。例えば↓ Bank::Bank(double initialChecking,double initialSavings):checking(initialChecking),savings(initialSavings){} これで全部かどうかは分かりません。(あと、質問の仕方が良くないなので、この様に回答が得られる事を当然とは思わないで下さい。) > なにかヒントやアドバイスお願いします 質問者さんがするべき事は、個人的に以下の事と思います。 (1) 第一にコンパイラの出力するエラーメッセージを理解できるようになること。 コンパイラが沢山のエラーを出力するかもしれませんが、一つ一つちゃんと意味のある事が書かれています。コンパイルエラーが出る度に人に聞くというのをいつまでも続けるのは許されない事なので、これらのメッセージをちゃんと理解できる様になるべきです。 コンパイルエラーは、沢山出ても慌てずに、「一つずつ」解決していく事が基本です。エラーメッセージには大抵、エラーが起こったファイル名と行番号が書かれていますので、先ずはその箇所を確認する癖をつけて下さい。それができるようになったら、エラーメッセージが具体的にどういう事を意味するのかを調べるなり聞くなりして、段々と理解できる様になれば良いでしょう。 (2) 第二に質問の仕方を覚えること。 これは冒頭で述べた通り何が問題点なのか誰が聞いても分かる様に説明する事です (まあ、分かりやすく説明するには慣れの問題もあるのですぐには難しいかも知れませんが意識する様にして下さい)。 私自身、質問の仕方に自信があるわけでもないのですが、例えば今回の場合においては以下の様に質問するのが一つのやり方だったかなと思います。 ----- コンパイルをしようとすると以下の様なエラーメッセージが表示されコンパイルできません。 (エラーメッセージのコピーペースト) このエラーメッセージはどの様な意味でしょうか。どの様な場合に起こる物でしょうか。 ----- ただし、大量に出たエラーメッセージを全部まとめて質問するのは止めて下さいね。飽くまで自分の分からなかったエラーの部分を抜き出して質問する事です。(何れにしても、自分自身で手を尽くしても解決できなかった場合に質問する事はもちろん前提ですよ。) これらさえ習得できれば、取り敢えずの所はただ真っ直ぐ前に進むだけです。頑張って下さい。

回答No.2

デタラメやないですか。 質問はコンパイル・エラーが消えてから。

  • kmee
  • ベストアンサー率55% (1857/3366)
回答No.1

具体的、どんなことをやろうとして、それがどんな風になる/ならない のでしょうか? それがわからなければ、「正解」を考えることができません。 明かなエラーとかを指摘することしかできません。 ・ account.h についての説明がありません。 どこにあるのでしょうか? > h22.h の中身 > #include <string> > #include "h22.h" ・h22.h の中にh22.hをincludeするのですか? ・Bankの実装部分が含まれますが、これは、ここに書こうとしたものですか? > Bank::Bank() > { > Account checking; > Account saving; > } Account checking、Account savingは「(コンストラクの中だけで有効な)ローカル変数」になります。 this->checking, this->savingとは別です。 このままでは無意味な宣言です。 > #include <iostream> > #include "acount.h" > using namespace std; ・acount.h はどこでしょう? account.hとは別ですか? > Account::Account (以下略) ・コンストラクタの定義だと思われますが、 ()がありません。 ・Account::Account(double) はクラスでの宣言がありません。 宣言されているのはAccount::Account(double&)です。 /* でも、ここで参照が必要でしょうか? */ ・Account::double deposit() const 等、あきらかに変です。 などなど、現行では、コンパイルもまともにできません。

関連するQ&A

  • C++ クラス定義の質問

    C++学習者です。Visual studio community 2015 を使っています。 銀行口座を表す SavingsAccount というクラスを作り、添付のプログラムをコンパイルしようとしましたが。以下のようなエラーメッセージが出てきました。 1>------ ビルド開始: プロジェクト:ConsoleApplication86, 構成:Debug Win32 ------ 1>savingsAccount.obj : error LNK2001: 外部シンボル ""private: static double SavingsAccount::annualInterestRate" (?annualInterestRate@SavingsAccount@@0NA)" は未解決です。 1>C:\Users\Shiro\documents\visual studio 2015\Projects\ConsoleApplication86\Debug\ConsoleApplication86.exe : fatal error LNK1120: 1 件の未解決の外部参照 ========== ビルド: 0 正常終了、1 失敗、0 更新不要、0 スキップ ========== ちゃんと値を代入しているのに、annualInterestRate が未解決とはどういうことなのでしょうか? 以下が、クラス定義ヘッダーファイル、クラス関数定義ファイル、クライアントプログラムです。どうかよろしくお願いいたします。 //**************************************** // クラス定義ヘッダーファイル //**************************************** #pragma once #ifndef SAVINGSACCOUNT_H #define SAVINGSACCOUNT_H class SavingsAccount { static double annualInterestRate; public: SavingsAccount(double); ~SavingsAccount(); static void modifyInterestRate(double); double calculateMonthlyInterest(); double getBalance() const; double getSavingsBalance() const; private: double balance; double savingsBalance; }; #endif //*************************************** // クラス関数定義ファイル //*************************************** // savingsAccount class member functions #include "stdafx.h" #include <iostream> using namespace std; #include "savingsAccount.h" double annualInterestRate = 0.03; SavingsAccount::SavingsAccount(double initialAmount) :balance(initialAmount) { savingsBalance = balance + calculateMonthlyInterest(); cout << "savings account with balance of " << balance << " and savings balance of " << savingsBalance << " has been constructed\n"; } SavingsAccount::~SavingsAccount() { cout << "savings account of the savings balance of " << savingsBalance << " has been destructed\n"; } void SavingsAccount::modifyInterestRate(double newRate) { annualInterestRate = newRate; } double SavingsAccount::getBalance() const { return balance; } double SavingsAccount::getSavingsBalance() const { return savingsBalance; } double SavingsAccount::calculateMonthlyInterest() { return balance * annualInterestRate / 12; } //******************************************** // クライアントプログラム //******************************************** // ConsoleApplication86.cpp : // class SavingsAccount driver program #include "stdafx.h" #include <iostream> using namespace std; #include "savingsAccount.h" int main() { SavingsAccount saver1(2000.00); SavingsAccount saver2(3000.00); cout << "original amount of saving for saver1 : " << saver1.getBalance() << " and savings with interest: " << saver1.getSavingsBalance() <<endl; cout << "----------------------------------\n"; cout << "original amount of saving for saver2 : " << saver2.getBalance() << " and savings with interest: " << saver2.getSavingsBalance() << endl; return 0; }

  • shared_ptr クラスについて

    shared_ptrクラスを使いたいのですが、使えません、どうしてでしょうか?ソースはこれです。 #include<iostream> #include <string> #include <fstream> #include<memory> using namespace std; class SMonster{ string name; int power; public: SMonster(); SMonster(int p); ~SMonster(){ }; void SetPower(int p); int GetPower(SMonster& t)const; void walk(const string& str); int GetPoint(void)const; }; class B {}; class D : public B {}; int main(void) { shared_ptr<D> sp0(new D); SMonster m(200); SMonster n(100); std::cout<<m.GetPower(m)<<std::endl; std::cout<<n.GetPower(n)<<std::endl; ShowWindow(10); }

  • C/C++関数間でのStringクラスの扱い

    以下のようなコードを実行してみましたが思い通りに動いてくれません. "sample"という文字列がstrへとコピーされると思ったのですが. stringクラスのc_str()メソッドはconst char*だと言っているので無理矢理キャストしたのが原因でしょうか.stringクラスは記憶領域を自動で変更してくれるのではないのですか.それともこの挙動は仕様ですか. -------- 以下コード -------- #include <iostream> #include <string> using namespace std; int func(char *); int main(void) {     string str("");     func((char *)str.c_str());     cout << "String: " << str << endl;     return EXIT_SUCCESS; } int func(char *buf) {     buf = "sample";     return 0; } -------- 以上コード --------

  • C++ クラスの作り方

    Windows10の上で、Visual Studio Community2015 を使ってC++を勉強中の者です。 Time クラスというのを定義して使おうとしましたが、クライアント側のプログラム作成中にエラーメッセージが出てきて、色々考えましたがどこが悪いのかわかりません。 プログラム自体は時刻を設定してそれを表示させるだけのものです。 詳しい方がいらっしゃいましたら、ご教授お願い致します。 問題のエラーメッセージ; "consoleApplication69.cpp" を作成中にエディターの中で、波型の赤線が出ているところにカーソルを持っていくと、次の3か所でそれぞれ次のようなエラーメッセージが出てきます。 (1) #include "time3.h" のところ: 「ソースファイルをひらけません。"time3.h"」 (2) 関数 incrementMinute( )のプロトタイプのところ:「不完全な型は使用できません。」 (3) 最初のパラメーター Time & のところ:「識別子 Time が定義されていません。」 以下に、 1: 私が作ったTimeクラスの定義のあるヘッダー "time3.h", 2: メンバー関数の定義ファイル "time3.cpp" 3:クライアント側プログラム "consoleApplication69.cpp" の3つのソースコードをコピーします。 "time3.cpp" については長いので、上の半分だけにしました。 ****************************************************** 1: "time3.h" ******************************************************** #pragma once // header file for Time class // time3.h #ifndef TIME3_H #define TIME3_H class Time { public: Time(int = 0, int = 0, int = 0); ~Time(); void setTime(int, int, int); void setHour(int); void setMinute(int); void setSecond(int); int getHour(); int getMinute(); int getSecond(); void printUniversal(); void printStandard(); private: int hour; int minute; int second; }; #endif *********************************************** 2: "time3.cpp" ************************************************ #include <iostream> #include <iomanip> #include <cstdlib> #include <ctime> #include <cmath> #include <cstring> #include "time3.h" using namespace System; using namespace std; Time::Time(int hr, int min, int sec) { setTime(hr, min, sec); } void Time::setTime(int hr, int min, int sec) { setHour(hr); setMinute(min); setSecond(sec); } void Time::setHour(int hr) { hour = (0 <= hr && hr <= 23) ? hr : 0; } void Time::setMinute(int min) { minute = (0 <= min && min <= 59) ? min : 0; } void Time::setSecond(int sec) { second = (0 <= sec && sec <= 59) ? sec : 0; } ********************************************************* 3: "consoleApplication69.cpp" ********************************************************* // ConsoleApplication69.cpp : メイン プロジェクト ファイルです。 #include "stdafx.h" #include <iostream> #include <iomanip> #include "time3.h" using namespace System; using namespace std; //prototype void incrementMinute(Time &, const int); int main() { Time t; t.setHour(2); t.setMinute(10); t.setSecond(30); cout << " current time is "; cout << setfill('0'); cout << setw(2) << t.getHour() << ":"; cout << setw(2) << t.getMinute() << ":"; cout << setw(2) << t.getSecond() << "\n"; return 0; } // function void incrementMinute(Time &tt, const int num) { // まだ未定義 } またソリューションエクスプローラーの画面写真も添付します。 ヘッダーファイルもインクルードしていますし、ソリューションの中に入れたつもりですが、なぜ Time が定義されていないといわれるのでしょうか? どうぞよろしくお願いいたします。

  • C言語のソートについて

    C言語で下記のファイルの中身を昇順と降順で出力しようとしているのですが、ソートが上手くいっていない状況です。 どなたか修正点を教えて頂けないでしょうか? 「ファイルの中身」 2022/11/14 16:19:56 4+4,8.000000 2022/11/14 16:20:14 7+7,14.000000 2022/11/14 16:20:18 8+8,16.000000 2022/11/15 16:19:56 4+4,8.000000 2022/11/14 16:20:14 7+7,14.000000 2022/11/18 16:20:18 8+8,16.000000 2022/11/17 16:19:56 4+4,8.000000 2022/11/14 16:20:14 7+7,14.000000 2022/11/14 16:20:18 8+8,16.000000 「ソースコード」 #include <stdio.h> #include <string.h> #include <stdlib.h> int cmp_u(const void* a, const void* d) { return *(char*)a - *(char*)d; } int cmp_d(const void* a, const void* d) { return *(char*)d - *(char*)a; } int main() { int r,i,n; FILE* fp; char sin[9][1000]; fp = fopen("log.txt", "r"); if (fp == NULL) { printf("ファイルオープン失敗\n"); return -1; } for (i = 0; i < 9; i++) { fscanf(fp, "%s", &(sin[i])); } fclose(fp); printf("ASC or DESC: "); scanf(" %s", &ad); if (strcmp(ad, "ASC") == 0) { qsort(sin, 9, sizeof(char), cmp_u); } else { qsort(sin, 9, sizeof(char), cmp_d); } for (i = 0; i < 9; i++) { printf("%s\n", sin[i]); } return 0; }

  • C++のファイルの分割について教えてください。

    分割したプログラムの書き方を練習中なのですが、 下のようなプログラムを書いて、ビルドしようとしたら失敗します。 どこが悪いのか、教えていただけないでしょうか? (5)\test30\Debug\test30.exe : fatal error LNK1120: 外部参照 1 が未解決です。 1>test30 - エラー 2、警告 0 ========== ビルド: 0 正常終了、1 失敗、0 更新不要、0 スキップ ========== //test30.cpp #include <iostream> #include "sub.h" int main(void) { std::cout<<"メインプログラムです。"<<std::endl; sub1(); sub2(); return 0; } ------------------------------------------------------------- //sub1.cpp #include <iostream> void sub1(void) { std::cout<<"サブ1です。"<<std::endl; } ------------------------------------------------------------- //sub2.cpp #include <iostream> void sub1(void) { std::cout<<"サブ2です。"<<std::endl; } --------------------------------------------------------------- //sub.h void sub1(void); void sub2(void);

  • C言語の質問です!

    #include "stdafx.h" #include <iostream> #include <string> #include <stdio.h> #include <math.h> #include <string.h> #include <stdlib.h> #include <time.h> #include <conio.h> using namespace std; double arrayMin(double array[][], int n){ double Min=9999999999999999999999.999999; for(int N=0;N<n;N++){ if(array[N][0]!=NULL&&array[N][0]<Min){ Min=array[N][0]; } } return Min; } double arrayMax(double array[][], int n){ double Max=-9999999999999999999999.999999; for(int N=0;N<n;N++){ if(array[N][0]!=NULL&&array[N][0]<Max){ Max=array[N][0]; } } return Max; } int main(){ double data[3][10] = {{2.0, 1.0, 5.0, 3.0, 2.0, 21.0, 4.0, 5.0, 4.0, 28.0}, {1.0, 1.0, 5.0, 3.0, 2.0, 21.0, 4.0, 5.0, 4.0, 28.0}, {3.0, 1.0, 5.0, 3.0, 2.0, 21.0, 4.0, 5.0, 4.0, 28.0}}; double min, max; min=arrayMin(data, 3); max=arrayMax(data, 3); printf("min = %lf, max = %lf\n", min, max); return 0; } 二次元配列の1行目の配列の最大値と最小値を求めることを考え,上のようなプログラムを書いたのですが, 1>.\maxmin.cpp(12) : error C2087: 'array' : 添字がありません。 1>.\maxmin.cpp(21) : error C2087: 'array' : 添字がありません。 1>.\maxmin.cpp(34) : error C2059: 構文エラー : ']' 1>.\maxmin.cpp(35) : error C2664: 'arrayMax' : 1 番目の引数を 'double [3][10]' から 'double [][1]' に変換できません。(新しい機能 ; ヘルプを参照) 1> 指示された型は関連がありません。変換には reinterpret_cast、C スタイル キャストまたは関数スタイルのキャストが必要です。 というようなエラーが出てしまいます. 途中のarray[N][0]!=NULLは二次元配列dataが3行より少ない場合に対応させています. どなたかアドバイスをいただけますでしょうか? よろしくお願いいたします!

  • デザパタ シングルトンクラスの実態宣言の場所について

    //-----singleton.h---------------------------------------- // Copyright(C) 2003 Yoshinori Oota All rights reserved. #ifndef SINGLTON #define SINGLTON #include <iostream> #include <string> using namespace std; class Singleton { public: static Singleton* Instance(); static void Destroy(); void nextState(); void printState() const; private: Singleton(); ~Singleton(); static Singleton* theInstance; string value_; }; //ここじゃだめなの? //Singleton* Singleton::theInstance = NULL; #endif //------------------------------------------------------- //-----singleton.cpp--------------------------------------- #include"singleton.h" Singleton* Singleton::theInstance = NULL; Singleton::Singleton() : value_("initial state") { } Singleton::~Singleton() { } Singleton* Singleton::Instance() { if (theInstance == NULL) { theInstance = new Singleton(); } return theInstance; } void Singleton::Destroy() { if (theInstance != NULL) { delete theInstance; theInstance = NULL; } } void Singleton::nextState() { if (value_ == "initial state") { value_ = "second state"; } else if (value_ == "second state") { value_ = "third state"; } else if (value_ == "third state") { value_ = "initial state"; } } void Singleton::printState() const { cout << value_ << endl; } //------------------------------------------------------ //----main.cpp------------------------------------------- #include"singleton.h" int main() { Singleton* theSingleton = Singleton::Instance(); theSingleton->printState(); theSingleton->nextState(); theSingleton->printState(); //デストラクタも隠蔽することにより、2重deleteを防げる Singleton::Destroy(); } //-------------------------------------------------------- デザパタのシングルトンを勉強していたのですが、 実態の宣言(Singleton* Singleton::theInstance = NULL;)はヘッダファイル内だとなぜだめなのでしょうか? さらにprivate修飾がついてるのに、なぜNULLにセットできるでしょう。 参照HP http://www002.upp.sonet.ne.jp/ys_oota/mdp/Singleton/index.htm

  • プログラムの説明

    C++の初心者です。 ↓のプログラムの動作はさっぱりわかりませんが、それについての説明は具体的に教えていただきたいです。(できれば、詳しく) #include <iostream> #include <string> int getNinzu(int ARGC, char *ARGV[]) throw (char const *){ if(ARGC!=2){ throw "Needs only one argument."; } int ninzu=std::atoi(ARGV[1]); if(ninzu<=0){ throw "Value is too small."; } return ninzu; } #include <cstdlib> #include <ctime> int randfive(){ static bool firsttime=true; if(firsttime){ firsttime=false; std::srand(std::time(NULL)); } return static_cast<int>(static_cast<double>(std::rand())/RAND_MAX*(5+1)); } #include <iomanip> int main(int ARGC, char* ARGV[]){ std::string cmdname=ARGV[0]; int ninzu; try{ ninzu=getNinzu(ARGC,ARGV); std::cout << std::setfill('0'); for (int i = 1; i <= ninzu; ++i) { int score = 0; for (int k = 0; k < 20; ++k) score += randfive(); std::cout << "C" << std::setw(5) << i << " " << score << '\n'; } }catch(char const *str){ std::cerr << str << std::endl << "Usage: " << cmdname << " ninzu" << std::endl; return 1; } }

  • C言語 アロー演算子

    このようなプログラムを作りたいのですが上手くいきません。 (入力と出力は必ずアロー演算子を使う。) <実行例> 番号を入力:1 名前を入力:taro 番号:1 名前:taro どなたかよろしくお願い致します #include <stdio.h> #include <string.h> typedef struct{ int no; char name[21]; }student; void in(student *std){ char namae[21]; int bango,i=0; scanf("%d", &bango); std->no = bango; while(1){ namae[i] = getchar(); if((i >= 20 ) || (namae[i] == '\n')) break; i++; } i++; namae[i] ='\0'; strcpy(std->name,namae); } void out(student *std){ printf("%d\n", std->no); printf("%s\n", std->name); } main(){ student person; in(&person); out(&person); return 0; }

専門家に質問してみよう