什么是替代的set object = null在C ++喜欢C# [英] what's the alternative of set object = null in C++ like C#

查看:151
本文介绍了什么是替代的set object = null在C ++喜欢C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似的功能:

MyClass1 mc1, mc0; //Single Object
MyClass2 mc2; //vector of MyClass1

mc1.Init(1);
mc2.Add(mc1);
mc1 = mc0;

mc1.Init(2);
mc2.Add(mc1);
mc1 = mc0;
//so on......



我真的想设置 mc1 = null 在开始的步骤,但不能在C + +。所以我保持一个从未初始化的 mc0 来做。
不要认为这是一个优雅的解决方案。
我的背景主要是关于C#和ASP.NET的管理(我认为C ++的非托管属性是我不能做对象= null的原因。对吗?)

I actually want to set mc1 = null before at the beginning of the step but cannot do that in C++. So I kept a never-initialized mc0 to do that. Don't think this is an elegant solution. My background was mainly about C# and ASP.NET which is managed.(I think the unmanaged attribute of C++ is the reason why I cannot do object = null. Right?)

推荐答案

这与语言是否被管理无关,而是与C ++的不同方法对象引用。在C#中,声明 MyClass mc; 将产生一个可以指向 MyClass null 。在C ++中, MyClass mc; 产生一个变量, MyClass - 对象实例完全包含在变量中,因此,变量不能 null 。如果你想要一个引用,通常使用一个指针 MyClass * mc = NULL; MyClass * mc = new MyClass();

This has nothing to do with whether the language is managed or not, but rather with C++' different approach to object references. In C#, the declaration MyClass mc; would produce a variable that may refer to a MyClass or be null. In C++, MyClass mc; produces a variable that is a MyClass - the object instance is wholly contained in the variable, and as such, the variable cannot be null. If you want a reference, you would typically use a pointer: MyClass * mc = NULL; or MyClass * mc = new MyClass();.

这篇关于什么是替代的set object = null在C ++喜欢C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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