C++ / 类编译和字符串属性:"expected `)' before '=' token"

C++ / Class compilation and string attribute : "expected `)' before '=' token"

本文关键字:编译 before token 属性 字符串 C++ expected      更新时间:2023-10-16

我正在尝试编译一类使用套接字发送邮件

但是,我在编译过程中遇到了错误:

在"="标记之前应为"(">

在我声明构造函数的行:

Mail(ipSMTP="serveurmail.com", port=25)

我怀疑问题来自 Mail(( 构造函数之前声明的两个字符串属性:

下面是 mail.h 文件的代码,包含 Mail 类声明:

#if defined (WIN32)
#include <winsock2.h>
typedef int socklen_t;
#elif defined (linux)
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define INVALID_SOCKET -1
#define SOCKET_ERROR -1
#define closesocket(s) close(s)
typedef int SOCKET;
typedef struct sockaddr_in SOCKADDR_IN;
typedef struct sockaddr SOCKADDR;
#endif
#include <string>
#include <iostream>

using namespace std;
class Mail
{
  private :
  public :
         SOCKET sock;
         SOCKADDR_IN sin;
         char buffer[255];
         int erreur;
         int port;
         string message;
         string ipSMTP;
          Mail(ipSMTP="serveurmail.com", port=25)
          {
               #if defined (WIN32)
                WSADATA WSAData;
                erreur = WSAStartup(MAKEWORD(2,2), &WSAData);
                 #else
                    erreur = 0;
                 #endif
               message = "";
               /* Création de la socket */
                sock = socket(AF_INET, SOCK_STREAM, 0);
                /* Configuration de la connexion */
                sin.sin_addr.s_addr = inet_addr(ipSMTP.c_str());
                sin.sin_family = AF_INET;
                sin.sin_port = htons(port);
          }
          ~Mail()
          {
               /* On ferme la socket précédemment ouverte */
                    closesocket(sock);
                    #if defined (WIN32)
                        WSACleanup();
                    #endif
          }
          void envoi()
          {
               //Instructions d'envoi d'email par la socket via le SMTP
          } 
};

您需要指定构造函数参数的类型,并为成员分配传递的值。

Mail(ipSMTP="serveurmail.com", port=25)
{

应该写成

Mail (string const& ipSMTP = "serveurmail.com", int port =25)
  : port (port), ipSMTP (ipSMTP) // constructor initializer list
{

在上面,我们使用构造函数初始值设定项列表分配成员变量,您可以在此处阅读有关它的更多信息:

[10.6] 我的构造函数应该使用"初始化列表"还是"赋值"?

Mail(ipSMTP="serveurmail.com", port=25)

应该是

Mail( std::string ipSMTP="serveurmail.com", int port=25)

您还应该从头文件中删除 using 指令:

using namespace std;

这是不好的做法,因为它会在全局命名空间中填充 std 的内容,只要您包含标头。

你需要:(1(指定参数的类型;(2(初始化相关数据成员:

Mail(std::string ipSMTP="serveurmail.com", int port=25)
: ipSMTP(ipSMTP), port(port)
{
...

参数具有类型。由于您可能想要初始化成员变量,因此您需要类似

Mail(const string& ipsmtp="serveurmail.com",int p=25) : ipSMTP(ipsmtp), port(p) {
    ...
}