在 Java 中像 C++ 一样创建结构 [英] Create a Struct In Java Like C++

查看:41
本文介绍了在 Java 中像 C++ 一样创建结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 java 中创建一个结构,比如 c++ :

i want to create an struct in java , like c++ :

struct MyStruct {
    int x;
};
#include <iostream>
int main() {
    MyStruct Struct;
    Struct.x = 0;
    std::cout << Struct.x;
    return 0;
}

有人可以帮我吗?

推荐答案

public class ircodes {
    public ircodes(String msg_id, String node_id, String frequency, String data) {
        this.hdr = new msg_hdr(4 + data.length(), Integer.parseInt(msg_id), Integer.parseInt(node_id));
        this.frequency = Integer.parseInt(frequency);
        this.data = data;
    }

    public class msg_hdr {
        int msg_len;
        int msg_id;
        int node_id;

        public msg_hdr(int msg_len, int msg_id, int node_id) {
            this.msg_len = 12 + msg_len;
            this.msg_id = msg_id;
            this.node_id = node_id;
        }
    }
    msg_hdr hdr;
    int frequency;
    String data;

    public ByteBuffer serialize() {
        ByteBuffer buf = ByteBuffer.allocate(hdr.msg_len);
        buf.putInt(hdr.msg_len);
        buf.putInt(hdr.msg_id);
        buf.putInt(hdr.node_id);
        buf.putInt(frequency);
        buf.put(data.getBytes());
        return buf;
    }
}

这篇关于在 Java 中像 C++ 一样创建结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆