我不确定为什么我的程序无法运行。它说User :: receiveMessage和User :: sendMessage必须返回一个值。我很抱歉,我对编程很新。
#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 :(得分:2)
我通过clang-format和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
返回类型:
void receiveMessage(...
如果确实需要返回int
,请在结尾处添加return
语句:
int receiveMessage(const char *messageString) {
...
return 0;
}
对于其他警告,您可以将char[]
全部替换为std::string
,但它们并不是那么糟糕。