gpt4 book ai didi

java - Java 中的 "CONST"

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:16:28 26 4
gpt4 key购买 nike

我对 java 中的“CONST”有疑问。

我想知道如何用 C 语言编写类似“const struct VAL &getVal()”的代码。

这里是示例代码。

public class test {
/* VAL is just structure-like class */
class VAL {
public int i;
};
private VAL val;

/* test class functions */
test() {
val = new VAL();
val.i = 1;
}

VAL getVal() {
return val;
}

/* main function */
public static void main(String[] args) {
test t = new test();
VAL t_val;

t_val = t.getVal();

t_val.i = 2; /* it should be error if t_val variable is a const */
System.out.printf("%d %d\n", t.getVal().i, t_val.i);
}
}

下面是 C 示例代码。

struct VAL
{
int i;
};

const struct VAL &getVal() /* THIS IS WHAT I WANT */
{
static VAL xxx;
return xxx;
}

int main()
{
const VAL &val = getVal();
val.i = 0; /* error */

VAL val2 = getVal();
val2.i = 0; /* it's not an error, but it's ok because it cannot be changed xxx variable in getVal() either. */

return 0;
}

最佳答案

final 关键字具有相似的语义。您不能更改对象的引用,但是如果对象是可变的,则可以更改对象本身。我建议用谷歌搜索并阅读更多相关信息。

关于java - Java 中的 "CONST",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6533415/

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