gpt4 book ai didi

java - 像 C++ 一样在 Java 中创建结构体

转载 作者:行者123 更新时间:2023-12-02 04:55:38 25 4
gpt4 key购买 nike

我想在 java 中创建一个结构,就像 c++ 一样:

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

谁能帮我吗?

最佳答案

您可以使用类,其功能类似于 C++ 中的struct

例如,C++ point 结构可能看起来像

typedef struct __point {
int x, y;
} point;

Java point 类具有以下形式

final class Point { 
private final double x; // x-coordinate
private final double y; // y-coordinate

// point initialized from parameters
public Point(double x, double y) {
this.x = x;
this.y = y;
}

// accessor methods
public double x() { return x; }
public double y() { return y; }

// return a string representation of this point
public String toString() {
return "(" + x + ", " + y + ")";
}

}

然后我们可以调用以下内容:

Point q = new Point(0.5, 0.5);
System.out.println("q = " + q);
System.out.println("x = " + q.x());

关于java - 像 C++ 一样在 Java 中创建结构体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28798152/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com