繁体   English   中英

C ++:为什么将转换作为指针然后解除引用工作?

[英]C++: Why does casting as a pointer and then dereferencing work?

最近我一直在使用C ++中的套接字,我遇到过这样的问题:

*(struct in_addr*)&serv_addr.sin_addr.s_addr = *(struct in_addr *)server->h_addr;

虽然这确实做了我想要的,但我有点困惑为什么我不能这样做:

(struct in_addr)serv_addr.sin_addr.s_addr = *(struct in_addr *)server->h_addr;

既然它成为指针然后立即被解除引用不应该第二次工作以及第一次工作? 我还是C ++的新手,这对我来说有点困惑。 任何帮助将不胜感激。 下面是代码。 它所做的就是获取主机名或IP并将IP打印到屏幕上。

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>


using namespace std;

int main(){

    int socketfd, portno, rwResult; 
    struct sockaddr_in serv_addr; 
    struct hostent* server;     
    char inputName[50];

    //The next block gets the host name and port number and stores them in variables
    cout<<"Enter host(Max Size 50): ";
    cin>>inputName;
    cout<<endl<<"Enter port number: ";
    cin>>portno;
    cout<<endl;

    server = gethostbyname(inputName);
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(portno);

    *(struct in_addr*)&serv_addr.sin_addr.s_addr = *(struct in_addr *)server->h_addr;
    //This is where I am confused
    //(struct in_addr)serv_addr.sin_addr.s_addr = *(struct in_addr *)server->h_addr;


    cout<< "Server: "<<inet_ntoa(*(struct in_addr *)server->h_addr_list[0])<<endl;

    cout<< "Server: "<<inet_ntoa(*(struct in_addr *)&serv_addr.sin_addr.s_addr)<<endl;
    //The two cout's tell me if the address was copied correctly to serv_addr I believe.



    return 0;
}

如果存在接受原始类型参数的构造函数,则对象只能转换为另一个类。

另一方面,指针可以毫无疑问地施放。 但是,这样做可能非常危险。 如果需要强制转换,请在执行此操作时使用static_cast或dynamic_cast,并可能检查强制转换是否成功。 以这种更明确的方式进行投射的另一个风格优势是它使得演员对于浏览代码的人更加明显。

代码正在尝试将serv_addr.sin_addr.s_addr重新解释为in_addr类型。 但是,此转换不兼容。 因此,如果您尝试直接强制转换,则会在第二个代码段中出现编译器错误。

在第一个片段中,您实际上是使用指针转换来解决此类型的不兼容问题。

一个更简单的例子可能有助于解释差异:

double q = 0.5;
int n;

n = (int) q;    // #1
n = *(int*)(&q) // #2

第一版本的 转换 q成类型的值int根据语言的规则。 转换仅适用于基本类型和定义转换运算符/构造函数的类。

第二个版本将q的二进制表示重新解释为整数。 在良好的情况下(如在您的示例中),这会产生一些有用的东西,但通常这是未定义的行为,因为不允许通过指向不同类型的指针访问一种类型的变量。

您的示例可能有效,因为有问题的两种类型都是具有相同初始成员的POD结构,并且您只访问其中一个常见的初始成员。 编辑。 我查了一下, server->h_addrchar *类型。 它可能只是一个占位符,指针实际上是一个正确类型的结构。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM