设置并获取类中不同类成员的值

时间:2013-06-28 15:13:27

标签: c++ member-functions

我是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;

}

我不确定上面的代码逻辑是否正确,有人可以帮助我如何继续它。 非常感谢

1 个答案:

答案 0 :(得分: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';