在C中的结构内部声明变量 [英] Declaring variables inside a struct in c

查看:68
本文介绍了在C中的结构内部声明变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为我的编程语言制作一个面向对象的预处理器,以便将我的语言转换为 C (类似于早期的C ++).我想用结构模拟类.问题是:如何在这样的结构中声明变量:

I wanted to make an object oriented preprocessor to my programming language which converts my language into C (like early C++). And I want to simulate the classes with structures. And the question is: how can I declare a variable inside a struct like this:

typedef struct { //equivalent of class
   int a = 5;
   int (*sub)(int) = &int_sub; //function of a class, uses an external declared function
} class_name;

我尝试了上面的代码,但编译器编写了以下代码:

I tried the code above but the compiler wrote this:

error: expected ‘:’, ‘,’, ‘;’, ‘}’ or ‘__attribute__’ before ‘=’ token 
       void (*sub)(int) = &int_sub;

我有两个问题:

  1. 我可以在结构内声明变量吗?

  1. Can I declare a variable inside a struct?

如果是,怎么办?

推荐答案

或者,您也可以初始化结构类型的变量.

Alternatively, you can also initialize the variable of your struct type.

int func( int a ){}

typedef struct {
    int a;
    int (*sub)(int);
} class_name;

class_name my_struct = { .a = 5, .sub = func };

这篇关于在C中的结构内部声明变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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