【发布时间】:2011-06-30 10:31:05
【问题描述】:
我对 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;
}
【问题讨论】:
-
为什么你需要这个结构是不可变的?如果问题在于它与不应在外部更改的数据结构有关,那么您可能会返回结构的副本而不是结构本身,因此返回结构的更改不会影响主数据结构。
标签: java