Why don't structs support inheritance?
来源:互联网 发布:mac 命令行安装apk 编辑:程序博客网 时间:2024/06/14 11:34
假设.net中的struct可以inherit。现有这样的代码:
BaseStruct a;SubStruct b; //inherits from BaseStruct, added fields, etc.a = b; //?? expand size during assignment?
这会出什么问题?因为struct是value type不是reference type,他们是copy by value,上面的a的size根本不能容纳下b。
所以.net不支持。
在native c++又是如何呢?
同样的代码在native c++中,是可以的:虽然通过了编译,但是功能上有问题(有object slice)。这就又回到了copy by value, copy by reference的问题上。如果上面的a和b都是指针(相当于.net中的reference type),同时重写了operat=(这个容易忘,所以容易出错),那么就不会有问题。c++给程序员提供了更多的控制权:new出来的在heap上,只能通过指针来引用;非new出来的,在stack上,按位copy。
不巧的是,.net中,在heap还是在stack上,不是又程序员决定的,而是由type决定的。.net天然地帮我们定好 了每种type是reference type还是value type。
.net这个有受限,c++这个强是强但容易出错,到底哪个好呢?应了一句话,权利越大,责任越重!自己选吧!
- Why don't structs support inheritance?
- Listen, Don't Look : Why
- Java only supports Single Inheritance, doesn’t support Multiple Inheritance
- Why Socialists Don't Believe In Fun
- Why don't we have virtual constructors?
- why vue.js doesn't support templateURL
- I don't know why I love Acronym
- why copy constructor don't need to check 3 things
- Why Programmers don’t have a High Social Status?
- Why I Don't Call It “GNU/Linux”
- [翻译]Why you don’t want to shard
- Unreal 入门-Anim Select Ue4 4.14 don't support
- Why doesn't Symbian OS support writeable static data?
- Why doesn't Symbian OS support writeable static data?
- Why doesn't Objective-C support private methods?
- Why don't we use a constructor instead of factory method?
- 我想骂人.....but i don't know why i do that?
- 为什么不选择软件测试? Why don't choice Software Testing?
- 孙鑫VC学习笔记 (图形的保存和重绘)
- js中prompt()的用法
- fork, vfork以及return, exit
- FreeEIM通讯软件平均需要5分钟才能
- 黑马程序员---银行业务调度系统
- Why don't structs support inheritance?
- android进程与线程详解一:进程
- JVM内存设置
- 官方标准版如何编译webrtc ( how to compile webrtc )
- 完美国际生产任务
- android进程与线程详解二:线程
- Ubuntu Cannot complete the install because of a conflicting dependency.
- android进程与线程详解三:AsyncTask
- 在当前窗体上对其他窗体及其控件进行操作