2016-12-07 78 views
0

我不知道爲什麼我的程序無法運行。它是說User :: receiveMessage和User :: sendMessage必須返回一個值。我很抱歉,我對編程相當陌生。C4716錯誤 - 必須返回值

#include <iostream> 
#include <string.h> 
#include <cstring> 

using namespace std; 
class User { 
public: 
    char username[16]; 
    char userMotto[64]; 

public: 
    User(char name[16], char motto[64]) { 
    strcpy(username, name); 
    strcpy(userMotto, motto); 
    } 

    int sendMessage(const char *messageString, User &otherUser) { 
    cout << "\n" << username << " is sending this message: " << messageString; 
    otherUser.receiveMessage(messageString); 
    } 

    int receiveMessage(const char *messageString) { 
    cout << endl << username << " received this message: " << messageString; 
    } 
}; 

int main() { 
    User sender("Bill", "I message, therefore I am"); 
    char message[64]; 
    cout << "Enter your Message to Send: "; 
    cin >> message; 
    User receiver("Ted", "I message, therefore I am"); 
    sender.sendMessage(message, receiver); 
    return 0; 
} 
+0

錯誤消息是不言自明的。你的'sendMessage'和'receiveMessage'函數有'int'返回類型,但是你沒有從它們返回任何東西。向他們添加'return(0)',或更改函數簽名。 – Ari0nhh

+0

你是什麼意思加回歸(0)給他們?所以我應該加入返回0;到用戶方法的結尾? – archeryninja

+0

'return(0);'不正確。它是'return 0;'。 –

回答

2

我通過鐺格式和an online Clang compiler通過您的代碼,這些都是錯誤信息:

prog.cc:20:3: warning: control reaches end of non-void function [-Wreturn-type] 
    } 
^

prog.cc:24:3: warning: control reaches end of non-void function [-Wreturn-type] 
    } 
^

prog.cc:28:15: warning: ISO C++11 does not allow conversion from string literal to 'char *' [-Wwritable-strings] 
    User sender("Bill", "I message, therefore I am"); 
      ^

prog.cc:28:23: warning: ISO C++11 does not allow conversion from string literal to 'char *' [-Wwritable-strings] 
    User sender("Bill", "I message, therefore I am"); 
        ^

prog.cc:32:17: warning: ISO C++11 does not allow conversion from string literal to 'char *' [-Wwritable-strings] 
    User receiver("Ted", "I message, therefore I am"); 
       ^

prog.cc:32:24: warning: ISO C++11 does not allow conversion from string literal to 'char *' [-Wwritable-strings] 
    User receiver("Ted", "I message, therefore I am"); 
        ^

要解決前兩個警告,您需要更改這些功能:

int receiveMessage(const char *messageString) { 
    cout << endl << username << " received this message: " << messageString; 
    } 

請問receiveMessage需要返回int?如果不是,將其更改爲void返回類型:

int receiveMessage(const char *messageString) { 
    ... 
    return 0; 
    } 

對於您可以更換其他警告:

void receiveMessage(... 

如果確實需要返回int,在末尾添加一個return聲明char[]std::string,但它們並不那麼糟糕。

相關問題