folgenden Code nicht kompilieren:g ++ Compiler-Optimierung: Konvertierung '<in geschweiften Klammern stehenden Initialisiererliste>'
Ah
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <fcntl.h>
namespace net {
using Ip = in_addr_t;
using Port = in_port_t;
using SockFd = int;
class Params final {
public:
Ip getIp() const { return ip_; }
Port getPort() const { return port_; }
private:
Ip ip_ {INADDR_ANY};
Port port_ {htons(5)};
};
}
A.cpp
#include <iostream>
#include "A.h"
int main(){
net::Params a {};
std::cout << "Ip=" << a.getIp() << ", Port=" << a.getPort() << std::endl;
return 0;
}
Zusammenstellung:
g++-6 -O2 -std=c++11 A.cpp
Fehler:
In file included from /usr/include/x86_64-linux-gnu/bits/byteswap.h:35:0,
from /usr/include/endian.h:60,
from /usr/include/ctype.h:39,
from /usr/include/c++/6/cctype:42,
from /usr/include/c++/6/bits/localefwd.h:42,
from /usr/include/c++/6/ios:41,
from /usr/include/c++/6/ostream:38,
from /usr/include/c++/6/iostream:39,
from A.cpp:1:
A.h:21:15: error: statement-expressions are not allowed outside functions nor in template-argument lists
Port port_ {htons(5)};
^
In file included from A.cpp:3:0:
A.h:21:23: error: cannot convert ‘<brace-enclosed initializer list>’ to ‘net::Port {aka short unsigned int}’ in initialization
Port port_ {htons(5)};
^
Aber wenn ich port_
Membervariable Initialisierung zu ändern: Port port_ {5};
, g ++ mit -O2 kompiliert in Ordnung.
Above Code kompiliert ohne Optimierung Flag fein, ob port_
initialisiert als: Port port_ {htons(5)};
oder als Port port_ {5};
Was ist falsch?
Ja, es funktioniert. Vielen Dank. Es ist peinlich, dass der Compiler von MS besser funktioniert als der von GNU. – UDPLover