【问题标题】:set and get the value of different class members in a class设置和获取类中不同类成员的值
【发布时间】:2013-06-28 15:13:27
【问题描述】:

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

}

我不确定上述代码逻辑是否正确,有人可以帮助我如何进行。 非常感谢

【问题讨论】:

  • 我相信你做对了。
  • 对我来说看起来不错,但如果你缩进你的代码会很好。许多人使用 m_ 作为 C++ 中成员数据的前缀。然后你可以使用 name 而不是 name1 等。
  • 但是如何在主函数中打印名称和持续时间。我需要打印std::cout &lt;&lt; " the name of the thesis is" &lt;&lt; thesis.name &lt;&lt; ; 吗?你能帮我解决这个问题吗

标签: c++ member-functions


【解决方案1】:

您已经编写了一些集合函数。您现在需要一些 get 函数。

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

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

由于数据现在是私有的,您无法从课堂外访问它。但是您可以在 main 函数中使用 get 函数。

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

【讨论】:

  • 感谢您的帮助。你能不能更新一下它有一个完整的程序。让我理解的更清楚。
  • 在类定义中添加方法。添加 std::cout 调用而不是注释“//打印名称和持续时间”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-04
  • 2012-02-10
相关资源
最近更新 更多