构造函数/析构函数是否必须有代码,还是函数足够? [英] Does a constructor / destructor have to have code, or is the function enough?

查看:225
本文介绍了构造函数/析构函数是否必须有代码,还是函数足够?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以如果我有一个类

class Transaction {

int no;
char dollar;

public:

    Transaction();
    ~Transaction();
}

在我的构造函数/析构函数中

And in my constructor / destructor

Transaction::Transaction {
    cout << "Entering constructor" << endl;
}

Transaction::~Transaction {
    cout << "Leaving program" << endl;
}

足以让我的构造函数和析构函数工作?

is that code enough for my constructor and destructor to work? Will it set the data members in my class to a safe state even though I declare nothing in my constructor?

推荐答案

您的课程已经在我的课程中设置了一个安全的状态,

Your class has only simple data members, so you don't even need (or should want) a destructor.

但是,你应该在构造函数中初始化你的数据成员:

You should, however, initialize your data members in the constructor:

Transaction::Transaction()
  : no(0), dollar('$') {
    cout << "Entering constructor" << endl;
}

否则,它们不会被初始化,并且可能包含随机值如果不在构造函数中初始化它们,则不能保证将原始非静态成员初始化为任何特定值)。如果你有指针成员,这可能是特别阴险。

Otherwise, they will not be initialized, and may contain random values (C++ doesn't guarantee initialization of primitive non-static members to any particular value if you don't initialize them in the constructor). This can be particularly insidious if you have pointer members.

这篇关于构造函数/析构函数是否必须有代码,还是函数足够?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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