C ++ struct可以有成员函数吗? [英] Can C++ struct have member functions?

查看:802
本文介绍了C ++ struct可以有成员函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对struct和类之间的区别非常困惑,因为我似乎看到他们用于几乎相同的事情。我搜索的差异,唯一的答案,我看到的结构具有公共成员默认和类有私人成员默认情况下。然而,我的讲师刚刚告诉我结构不能包含成员函数。但我已经在互联网上看到许多线程,人们包括结构中的成员函数,并具体说,这是可以这样做。

I was pretty confused about the difference between struct and class as I seemed to see them used for pretty much the same things. I googled the differences and the only answer I saw was that structs have public members by default and classes have private members by default. However, my lecturers have just told me that structs cannot contain member functions. But I have seen many threads on the internet where people include member functions in structs and specifically say that it is alright to do so.

我的讲师似乎坚定的结构定义不能有功能,所以发生了什么事?我唯一能想到的是,也许编译器将一个结构中的函数改为其他的,使它们在技术上不包含函数...这些矛盾有明确的答案吗?

My lecturers seem adamant that structs by definition cannot have functions, so what is going on? The only thing I could think of is that maybe the compiler changes functions within a struct to something else so that they technically don't contain functions... Is there a clear answer to these contradictions?

推荐答案


我搜索的差异,唯一的答案,我看到结构有默认的公共成员和类有私人成员默认。 / p>

I googled the differences and the only answer I saw was that structs have public members by default and classes have private members by default.

是的,这是正确的。另外,默认情况下,结构的基址是公开继承的,而类的基址默认是继承的。

Yes, this is correct. In addition, bases of a struct are inherited publicly by default, whereas bases of a class are inherited privately by default.

将函数声明为结构体的成员与声明函数作为类的成员相同的语义,除了你注意到的差异。在每种情况下,它们被称为成员函数

Declaring a function as a member of a struct has precisely the same semantics as declaring a function as a member of a class, except for the difference you've noted. In each case they are called member functions.

这篇关于C ++ struct可以有成员函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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