如何使`return`返回var和text

时间:2017-12-19 00:48:00

标签: c++ return

我有这段代码:

#include <iostream>
#include <string>
using namespace std;

class Event{
    public:
        Event(int x, int y, string z){
            setEvent(x, y, z);
        }//Constructor

        void setEvent(int a, int b, string c){
            if(a >= 0){
                if(a < b){
                    if(b <= 24){
                        start_time = a;
                        end_time = b;
                        event_name = c;
                    }
                    else cout <<"The end time for the event needs to be <=24 hours";
                }
                else cout <<"The start time for the event needs to be smaller than the end time";
            }
            else cout <<"The start time for the event needs to be >=0 hours";
        }//Code to set an event and check if the event is valid within the precondition

        void rename(string r){//Code to rename event
            event_name = r;
        }

        string duration(){
            int time_length = end_time - start_time;
            if(time_length == 1) return "1 hour";//I am stuck over here!!!
            else return time_length "hour";
        }

    private:
        int start_time;
        int end_time;
        string event_name;
};

如果你在公共类中查看void duration(),我试图让return在一个部分中返回文本,在另一部分中返回var和text。但我无法使其发挥作用。

     main.cpp:30:16: error: could not convert 'time_length' from 'int' to 'std::__cxx11::string {aka std::__cxx11::basic_string<char>}'
else return time_length "hour";
            ^~~~~~~~~~~

main.cpp:30:28:错误:预期';'字符串常量之前     否则返回time_length“小时”;                             ^ ~~~~~

有没有办法使return工作或任何替代方法来修复此问题/代码。

1 个答案:

答案 0 :(得分:1)

使用void表示该函数不会返回任何内容,因此您实际上无法从此函数中检索任何变量。

修复方法是给函数类型std::string,EG

string duration(){
    int time_length = end_time - start_time;
    if(time_length == 1) return "1 hour";//I am stuck over here!!!
    else //Formulate a string otherwise
}

请注意,您将不得不查看building a string with C++,并将该逻辑放入您的else语句中。

如果您希望返回一对,则必须编写另一个返回类型为std::pair<int, std::string>的函数