简体   繁体   English

C结构中的函数定义?

[英]Function definition in C struct?

I have a C code I need to understand. 我有一个我需要了解的C代码。 There is a 有一个

typedef struct someStruct {
    int i; 
    char c; 
    someStruct() {
        i = 0;
        c = 'c';
    }
    someStruct(char inpChar) {
        i = 1;
        c = inpChar;
    }
} t_someStruct;

(The code doesn't really make sense or serve a purpose, I know. I just simplified it.) So there is this structure and it has two members (int i and char c). (我知道,代码并没有真正意义或目的。我只是简化了它。)因此,存在这种结构,它具有两个成员(int i和char c)。 The interesting part is that it has basically two constructors, which is a new concept to me. 有趣的是它基本上有两个构造函数,这对我来说是一个新概念。 It works normally, but can we write constructors for structures? 它可以正常工作,但是我们可以为结构编写构造函数吗? I couldn't find anything on Google, maybe I am not searching right. 我在Google上找不到任何内容,也许我搜索不正确。

Your code is not valid C code (ie valid C11 ) code but it is valid C++ (ie C++14 ) code. 您的代码不是有效的C代码(即有效C11 )代码,但它是有效的C ++(即C ++ 14 )代码。

In C++, a struct is like a class except that all members are by default public ; 在C ++中,除了默认情况下所有成员都是public之外, struct类似于class see eg here . 见例如这里

There are no constructors in C. C中没有构造函数。

This code is most probably in C++. 此代码很可能是C ++。 In C++, a struct is actually similar to a class , hence you can define constructors for structs in C++. 在C ++中, struct实际上类似于class ,因此您可以在C ++中为结构定义构造函数。

Try to compile your code in gcc. 尝试在gcc中编译代码。 You'll get a 你会得到一个

error: expected specifier-qualifier-list before ‘someStruct’

The main difference between C and C++ is that C++ supports class but C does not. C和C ++之间的主要区别是C ++支持类,但C不支持。 In C++ struct is a special class so the above code will work in C++ but not in C. 在C ++中struct是一个特殊的类,因此上述代码将在C ++中起作用,但在C中不起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM