2017-11-01 3 views
2

私はクラスの一部である文字列にアクセスしたいと思っています。たぶん私もクラスにそれらを取得することはできませんC++でクラスのオブジェクトのStringを返すにはどうすればよいですか?

#include<iostream> 
#include<string> 
#include<vector> 


class element { 
    std::string Name; 
    int Z; 
    double N; 
    public: 
    element (std::string,int,double); 
    double M (void) {return (Z+N);} 
    std::string NameF() {return (Name);} 
}; 

element::element (std::string Name, int Z, double N) { 

    Name=Name; 
    Z=Z; 
    N=N; 
} 

int main() { 


    element H ("Hydrogen",1,1.); 
    element O ("Oxygen",8,8); 

    std::vector<element> H2O ={H,H,O}; 

    std::cout<<"Mass of " <<O.NameF()<<" is: " << O.M() << std::endl; 
    std::cout<<H2O[1].NameF()<<std::endl; 

    return 0; 
    } 

私はクラスで私のオブジェクトのうち、文字列を取得することはできませんよ... : は、ここではサンプルコードです。 標準のコンストラクタは文字列のように機能しますか? 私は呼び出すことができるオブジェクトの刺すような(つまり名前)をしたいだけです。 これを行うには適切な方法はありますか?

私は、パラメータの名前としてメンバーの名前を使用する場合は、あなたがthisポインタを経由してメンバーにアクセスする必要がある、

歓声 ニコ

+3

'名=名;'自体に関数パラメータを割り当て、に何もしませんメンバー。 – aschepler

+4

メンバ変数とパラメータの間の名前の衝突です。 [Member Initiallizer List](http://en.cppreference.com/w/cpp/language/initializer_list)はここで – user4581301

+3

または 'this-> Name = Name'を助けることができますが、実際にはパラメータまたはメンバー名を変更するだけです。 –

答えて

3

を任意の助けをいただければと思います。

ので変更:

Name=Name; 

this->Name = Name; 

し、同じことが他の二つのために行く:

this->Z = Z; 
this->N = N; 
4

のコンストラクタあなたは初期化リストを使用する必要がありますどこにイラーは、パラメータとメンバーの違いを知っている:

class element { 
    std::string Name; 
    int Z; 
    double N; 
    public: 
    element (std::string,int,double); 
    double M (void) {return (Z+N);} 
    std::string NameF() {return (Name);} 
}; 

element::element (std::string Name, int Z, double N) 
: Name(Name), Z(Z), N(N) // <- the compiler knows which is parameter and which is member 
{ 
    // no need to put anything here for this 
} 

そうしないと、thisを使用して、明示的に区別することができます

void element::set_name(std::string const& Name) 
{ 
    // tell the compiler which is the member of `this` 
    // and which is the parameter 
    this->Name = Name; 
} 
関連する問題