如何使`return`返回var和text

问题描述 投票:-3回答:1

我有这个代码:

#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工作或任何替代方案来解决这个问题/代码。

c++ return
1个回答
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>的函数

© www.soinside.com 2019 - 2024. All rights reserved.