构造函数&析构函数 [英] Constructor & Destructor

查看:107
本文介绍了构造函数&析构函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class a()
{
a();
`~a();
}
class b()
{
b();
~b();
}





执行Constructor&的顺序是什么?析构函数?



What will be the order for execution of Constructor & Destructor?

推荐答案

在实例化(创建)类的对象时调用构造函数,并在销毁对象时调用析构函数。这不是你如何在源代码中编写代码而是遵循生命周期类对象的规则的问题。
The contructor is called when an object of the class is instantiated (created) and the destructor is called when the object is destroyed. It is not a question of how you code it in your source but of following the rules for the life-cycle class objects.


你的代码没有意义:你不能有括号在类声明之后类a ()
Your code doesn''t make sense: you cannot have parenthesis after a class declaration class a().


那么你的代码就不会编译所以问题有点没有实际意义。为了让您的代码能够编译,您必须按照以下方式重写它:



Well your code won''t compile so the question is a bit moot. To get your code to compile you''d have to rewrite it along the lines of the following:

class a
{
    a();
    ~a();
};

class b
{
    b();
    ~b();
};





不幸的是,在这一点上它实际上什么都不做 - 你所做的就是描述编译器的一对类,实际上并没有让它做任何事情。



但是只要你真正尝试创建a或b类型的对象,编译器就会抱怨对象的构造函数是私有的,它不能创建那些类型的对象。



当你修复它时你可能会发现链接器抱怨它找不到a :: a(),a ::〜a(),b :: b()和b :: ~b()的定义。当你修复那个时候你会有一个你可以执行的程序并找到你想知道的答案。



干杯,



Ash



Unfortunately it won''t actually do anything at this point - all you''ve done is describe a pair of classes to the compiler and not actually told it to do anything.

However as soon as you actually try and create objects of type a or b the compiler will complain that the constructors for the objects are private and it can''t create objects of those types.

When you fix that you''ll probably find the linker complaining that it can''t find definitions of a::a(), a::~a(), b::b() and b::~b(). By the time you fix that lot you''ll have a program that you can probably execute AND find out the answers to what you want to know.

Cheers,

Ash


这篇关于构造函数&析构函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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