2013-06-28 4 views
0

저는 C++ 프로그래밍에 새로운 것이므로 프로젝트의 이름과 기간을 표시하는 간단한 클래스 프로그램을 작성했습니다.클래스에서 다른 클래스 멤버의 값을 설정하고 얻습니다.

#include<iostream> 
class project 
{ 

public: 
std::string name; 
int duration; 
}; 

int main() 
{ 
project thesis; // object creation of type class 
thesis.name = "smart camera"; //object accessing the data members of its class 
thesis.duration= 6; 

std::cout << " the name of the thesis is" << thesis.name << ; 
std::cout << " the duration of thesis in months is" << thesis.duration; 
return 0; 

하지만 이제는 클래스의 get 및 set 멤버 함수를 사용하여 동일한 패러다임을 프로그래밍해야합니다. 나는 다소 비슷하게 프로그램 할 필요가있다

#include<iostream.h> 

class project 
{ 

std::string name; 
int duration; 

void setName (int name1); // member functions set 
void setDuration(string duration1); 

}; 

void project::setName(int name1) 

{ 

name = name1; 

} 


void project::setDuration(string duration1); 

duration=duration1; 

} 

// main function 

int main() 
{ 
project thesis; // object creation of type class 

thesis.setName ("smart camera"); 
theis.setDuration(6.0); 


//print the name and duration 


return 0; 

} 

위의 코드 논리가 정확한지 여부를 잘 모르겠다. 감사합니다.

+0

나는 그것이 정확했다고 생각합니다. – 0x499602D2

+0

코드를 들여 쓰면 멋지 겠지만 나에게 잘 어울립니다. 많은 사람들은 C++에서 멤버 데이터의 접두사로 m_를 사용합니다. 그러면 name1보다는 이름을 사용할 수 있습니다. – Bathsheba

+0

main 함수에서 이름과 지속 시간을 출력하는 법. 'std :: cout << "을 출력해야합니까?"thesis.name <<;'입니까? 도와 주셔서 감사합니다 – user2532387

답변

1

일부 설정 기능을 작성했습니다. 이제 get 함수가 필요합니다.

int project::getName() 
{ 
    return name; 
} 

std::string project::getDuration() 
{ 
    return duration; 
} 

데이터가 이제 비공개이므로 클래스 외부에서 데이터에 액세스 할 수 없습니다. 그러나 주 함수에서 get 함수를 사용할 수 있습니다.

std::cout << " the name of the thesis is" << thesis.getName() << '\n'; 
std::cout << " the duration of the thesis is" << thesis.getDuration() << '\n'; 
+0

도와 주셔서 감사합니다. 전체 프로그램을 업데이트하십시오. 그래서 나는 더 명확하게 이해할 것이다. – user2532387

+0

클래스 정의 내에 메소드를 추가하십시오. 주석 대신 std :: cout 호출을 추가합니다 "// 이름 및 기간 인쇄" – doctorlove