私はC++でuniの研究を続けていますが、ポインタ、const引数、およびクラス実装の非常に基本的な点に関するいくつかの深刻な理解の問題に取り組んでいます。 C++)関数内のC++ const引数
私は通常Javaで動作するので、C++は非常に新しくなっています。
これは、クラスのための私の単純なヘッダ「人」である:
#ifndef Person_h
#define Person_h
class Person
{
private:
char* name;
char* adress;
char* phone;
public:
Person();
Person(char const *name, char const *adress, char const *phone);
Person(const Person &other);
~Person();
void setName(char const *name);
char* getName() const;
void setAdress(char const *adress);
char* getAdress() const;
void setPhone(char const *phone);
char* getPhone() const;
};
#endif // !Person_h
そしてここで問題が開始されます。実際のchar変数の代わりにcharポインタを使用するのはなぜですか?メモリを節約したり、パフォーマンスを向上させるための規則がいくつかありますか?
これが私たちの教授コードの方法であると私たちは、ポインタを使用することを理解させるためにしようとconst
など
今ここにクラスの私の実装です:
#include "Person.h"
//Person.h class implementation
Person::Person()
{
Person::name = new (char[64]);
Person::adress = new (char[64]);
Person::phone = new (char[64]);
}
Person::Person(const char *name, const char *adress , const char *phone)
{
Person::name = new (char[64]);
Person::adress = new (char[64]);
Person::phone = new (char[64]);
setName(name);
setAdress(adress);
setPhone(phone);
};
Person::Person(Person const &other)
{
Person::name = new (char[64]);
Person::adress = new (char[64]);
Person::phone = new (char[64]);
setName(other.getName);
setAdress(other.getAdress);
setPhone(other.getPhone);
};
Person::~Person()
{
delete [] name;
delete [] adress;
delete [] phone;
};
void Person::setName(const char *name)
{
this->name = name;
};
char* Person::getName() const
{
return name;
};
void Person::setAdress(char const *adress)
{
this->adress = adress;
};
char* Person::getAdress() const
{
return adress;
};
void Person::setPhone(char const *phone)
{
this->phone = phone;
};
char* Person::getPhone() const
{
return phone;
};
我々は手動で割り当てることを学ぶ必要がありますメモリを要素に割り当て、全体的なメモリ管理に注意してください。したがって、setter関数のconst引数の使用。私は要素の議論を変えないためにこれがあると思いますか?私は非常に困惑している、基本的には...
そして、私のIDE(MS VisualStudioを2015年)は、エラーとして次の行を強調:
void Person::setName(const char *name)
{
this->name = name; //error
};
「型の値 'のconstのchar *が' に割り当てることはできません'char *'型のエンティティ
これらの値を割り当てることができない場合、なぜconst
を使用する必要がありますか?または、メンバー変数自身を変更せずに、それらをどのように "un const"することができますか?const
?
この全体の問題は今私にとって大きな混乱の1つに過ぎません。
EDIT:I 私の試験にC-文字列を使用するのは、私たちの教授を参照するポインタとメモリ管理を理解するためです。
>実際のchar変数の代わりにcharポインタを使用するのはなぜですか? < あなたは、それのための 'std :: string'があります。 – myaut
裸のポインタではなく、文字列データを保持するために 'std :: string'を使うべきです。あなたに良いC++の本が必要なように私に見えます。 – Bathsheba
Cスタイルの文字列を割り当てるときは、文字列値をコピーするのに '='ではなく 'strcpy'を使います。 –