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