2013-06-28 27 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

看起來不錯,雖然如果你想縮進你的代碼會很好。許多人使用m_作爲C++成員數據的前綴。然後你可以使用name而不是name1等。 – Bathsheba

+0

但是如何在主函數中打印名字和持續時間。我是否需要打印'std :: cout <<「論文的名稱是」<< thesis.name <<;'?你能幫我在這 – user2532387

回答

1

你已經寫了一些設置功能。你現在需要一些獲取函數。

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