2017-11-01 1 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; 
    } 

내가 어쩌면 나는 심지어 클래스로 그들을 얻을 수 없습니다 ... 수업 시간에 내 개체에서 문자열을 얻을 수 아니다 : 다음은 예제 코드입니다. 표준 생성자가 문자열과 함께 작동합니까? 방금 ​​호출 할 수있는 물체의 흔적 (즉 이름)을 원합니다. 적절한 방법은 무엇입니까? 당신이 매개 변수의 이름으로 멤버의 이름을 사용하는 경우 내가 어떤 도움을 주셔서 감사합니다 것

,

환호 니코

+3

'이름 = 이름 : 명시 적으로 this를 사용하여 그렇지 않으면 차별화 할 수

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 } 

: iler는 매개 변수와 부재 사이의 차이를 알고 회원. – aschepler

+4

멤버 변수와 매개 변수 간의 이름 충돌입니다. [Member Initiallizer List] (http://en.cppreference.com/w/cpp/language/initializer_list)는 여기서 – user4581301

+3

또는'this-> Name = Name'을 도울 수 있지만 실제로 매개 변수 나 멤버 이름 만 변경하면됩니다. –

답변

3

, 당신은 this 포인터를 통해 멤버에 액세스해야합니다.

그래서 변경 :

Name=Name; 

this->Name = Name; 

에 그리고 같은 다른 두 간다 :

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

를 들어 생성자는 당신이 초기화 목록을 사용한다 어디 컴 `자체 함수 매개 변수를 할당하고,에 아무것도하지 않는다;

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; 
} 
관련 문제