c ++中的类的实例 [英] Instance of class in c++

查看:107
本文介绍了c ++中的类的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想问这个之间有什么区别

I woud like to ask what is the difference between this

Tv *television = new Tv();

Tv television = Tv();


推荐答案

第一个创建动态分配 Tv 并将其绑定到 Tv 的指针。 Tv 对象的持续时间在您的控制之下:您决定何时通过调用 delete 来销毁它。 / p>

The first one creates a dynamically allocated Tv and binds it to a pointer to Tv. The duration of the Tv object is under your control: you decide when to destroy it by calling delete on it.

new Tv(); // creates dynamically allocated Tv and returns pointer to it
Tv* television; // creates a pointer to Tv that points to nothing useful
Tv* tv1 = new Tv(); // creates dynamicalls allocated Tv, pointer tv1 points to it.

delete tv1; // destroy the object and deallocate memory used by it.

第二个创建自动分配 Tv 复制初始化。对象的 Tv 对象的持续时间是自动的。它根据语言的规则被确定性地破坏,例如,退出范围:

The second one creates an automatically allocated Tv by copy initialization. The duration of the Tv object is automatic. It gets destroyed deterministically, according to the rules of the language, e.g. on exiting scope:

{
  // copy-initializaiton: RHS is value initialized temporary.
  Tv television = Tv(); 
} // television is destroyed here.

退出范围也可以指类的对象的生命周期结束, Tv 对象:

"exiting scope" may also refer to the end of the life of an object of a class that contains a Tv object:

struct Foo {
  Tv tv;
}

....
{
  Foo f;
} // f is destroyed, and f.tv with it.

这篇关于c ++中的类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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