###前提・実現したいこと
C++で下記のように、コンストラクタ内でchar* plan を初期化したいと考えています。
そのためコンストラクタ内でnewを用いて、記憶空間を確保しました。
もしnewを記載せず、ヘッダのクラス定義の中で plan[100]と定義したら、エラーが起きましが、なぜですか。
###ソースコード
<メイン文> #include <iostream> #include <string.h> #include "Phone.h" using namespace std; Phone::Phone(){ plan = new char[100]; cout << "this is constrcuter "<< "\n"; this->i = false; strcpy(this->plan, "normal"); this->pInfo = "nokia"; } Phone::~Phone(){ } void Phone::ShowPhone(){ cout << " i = " << this->i << "\n"; cout << " plan = " << this->plan <<"\n"; cout << " pInfo = " << this->pInfo <<"\n"; } int main(){ cout << " main " <<"\n"; Phone p1; p1.i = false; strcpy(p1.plan,"normal"); p1.pInfo = "nokia"; p1.ShowPhone(); return 0; } <ヘッダー文> #include <string.h> class Phone{ public: Phone(); Phone(bool i, char* plan, std::string pInfo); ~Phone(); bool i; char* plan; std::string pInfo; virtual void ShowPhone(); };
###補足情報(言語/FW/ツール等のバージョンなど)
paiza.io
回答2件
あなたの回答
tips
プレビュー