函数应该返回什么C++

What C++ function should return?

本文关键字:什么 C++ 返回 函数      更新时间:2023-10-16

我有以下代码片段:

 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;
}

但它没有用。

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

struct tm * data_emprestimo
声明指向结构的指针,

因此要将结构本身作为值返回,您需要取消引用指针,return *data_emprestimo; .

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

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