【问题标题】:What C++ function should return?应该返回什么 C++ 函数?
【发布时间】:2012-12-04 16:21:49
【问题描述】:

我有以下sn-p的代码:

 time_t data1 = time(0)+86400; 
 struct tm * data_emprestimo = localtime( & data1 );
 cout << "Hoje: " << data_emprestimo->tm_mday << '/' << (data_emprestimo->tm_mon + 1) << '/' << (data_emprestimo->tm_year + 1900) << endl;

效果很好。

但我想知道我应该在函数中返回什么类型来获取 cout 回显并放入变量:struct tm?只是tm?大批?字符串?

我尝试过这样的事情:

struct tm retornaData(int segundosAdd);
            ...
            ...
struct tm retornaData(int segundosAdd){
   return data_emprestimo;
}

但它不起作用。

我已经用谷歌搜索了很多!

【问题讨论】:

  • 你想得到data_emprestimo-&gt;tm_mday
  • 我想要这个返回格式 -> '2012-12-17'
  • 你真的应该把它翻译成英文。现在可读性降低了。
  • 返回 struct something 是面向 C 的,C++ 不太一样。你应该先学习 C++ ;)
  • skp,你看我的问题了吗? “我是 C++ 的初学者……”

标签: c++ time-t


【解决方案1】:
struct tm * data_emprestimo

声明一个指向结构的指针,因此要将结构本身作为值返回,您需要取消引用指针return *data_emprestimo;

【讨论】:

    【解决方案2】:

    在我看来,您希望编写一个返回日期字符串表示的函数。

    在 c++ 中,std::string 将是字符串数据的自然返回类型。 更 C 风格的方法可能建议您传入 char * 作为您希望打印日期的缓冲区 - 通常 std::string 被认为是一种更清洁、更健壮的方法。

    【讨论】:

      猜你喜欢
      • 2018-09-03
      • 2019-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-18
      • 2020-07-16
      • 1970-01-01
      相关资源
      最近更新 更多