2017-12-19 14 views
-3

을 반환 return` : 공용 클래스 void duration()을 보면만들려면`나는이 코드를 가지고 VAR 및 텍스트

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

을, 나는 return 반환 한 부분의 텍스트와 VAR을 만들려고 노력하고 있어요 다른 부분의 텍스트. 그러나 나는 그것을 작동하게 할 수 없다.

 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 : 오류 : 예상 ';' 문자열 상수보다 전에 else time_length "hour"; ^ ~~~~~

return을 해결하거나이 문제/코드를 해결할 수있는 방법이 있습니까?

+1

1을 다른 함수를 작성해야 할 것입니다. 두번째는'std :: pair '과 같은 것을 반환한다. – user0042

+0

downvote를주는 대신 의견을 말하십시오. –

+0

@ user0042 당신이 의미하는 2 번째를 설명 할 수 있습니까? 당신이 의미하는 것이 불분명합니다. –

답변

1

void을 사용하면 함수가 아무 것도 반환하지 않으므로이 함수에서 실제로 변수를 검색 할 수 없습니다.

수정 사항은 building a string with C++에보고해야 할 것 함수 타입 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 
} 

주의를주고, 당신의 else 문에 그 논리를 넣어하는 것입니다.

당신이 한 쌍을 반환하려면

, 당신은 당신이 **`void` ** 함수에서 아무것도 반환 할 수 반환 형식으로 모든 std::pair<int, std::string>