3

在 C 语言中是否有可能发生这样的事情:

typedef struct S {
    char a;
    int b;
    int c = this.a * 60 + this.b;
} S;

这种类型的结构在我的代码中将非常有用。

4

5 回答 5

3

不,C如果你不能在声明中分配记忆值,那将是编译时错误。

但我可以建议一种解决方案(可能是你喜欢的):

#define INIT(this, a, b)  {a, b, (this).a * 60 + (this).b}

并称之为:

S s = INIT(s, '5', 6);
于 2013-07-22T09:53:53.217 回答
2

不,但您可以创建一个为您进行初始化的工厂函数:

// With a name like alloc, it's clear that the 
// user is responsible for freeing the memory allocated.
S* alloc_s(char a, int b) {
    S* s = malloc(sizeof(S));
    s->a = a;
    s->b = b;
    s->c = s->a * 60 + s->b;
    return s;
}
于 2013-07-22T09:58:32.933 回答
1

不,C(甚至 GNU C)中没有这样的特性。您不能有结构对象成员的默认值。

于 2013-07-22T09:53:19.823 回答
0

不,你不能。它会在编译时触发错误。但是,如果您希望 c 具有一定的价值,您可以这样做: static const int c = 666;

于 2013-07-22T09:55:03.660 回答
0

在不知道 a 和 b 的情况下,您无法计算表达式。你可以像这样模拟这个类:

#include <stdio.h>
#include <stdlib.h>

struct S;

typedef  struct S {
    char a;
    int b;
    int (*getC)(struct S* sss);
} S;

int getC(S* sss) { return sss->a*60+sss->b; }

S* make_S()
{
    S* p = (S*)malloc(sizeof(S));
    if(p==NULL) return NULL;
    p->getC = &getC;
    return p;
}

int main()
{
    S* s1 = make_S();

    s1->a = 1;
    s1->b = 2;
    printf("%i\n", s1->getC(s1));
    free(s1);
    return 0;
}
于 2013-07-22T09:55:18.227 回答