C ++:初始化一个成员指针为null? [英] C++: Initialize a member pointer to null?

查看:109
本文介绍了C ++:初始化一个成员指针为null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类如下:

class Foo
{
public:
    Foo();
    virtual ~Foo();

private:
    Odp* bar;
};

我想初始化 bar NULL 。这是最好的方法吗?

I wish to initialize bar to NULL. Is this the best way to do it?

Foo::Foo() : bar(NULL)
{
}

此外,析构函数是否必须是虚函数? (如果是真的,那么构造函数也必须是虚拟的)

Also, is it necessary that the destructor is virtual? (If that is true, then must the constructor be virtual as well?)

推荐答案


以初始化 bar NULL 。这是最好的方法吗?

I wish to initialize bar to NULL. Is this the best way to do it?

这是正确的方式。所以,是的。

It is the correct way. So, yes.


此外,析构函数是否必须是虚拟的?

Also, is it necessary that the destructor is virtual?

否。如果你将继承 Foo 类,并且将使用 Foo 指针,析构函数只需要是virtual删除这些派生类(虽然作为一般的经验法则,如果有任何其他虚拟成员,它应该是虚拟的)。

No. The destructor only needs to be virtual if you will be inheriting from the Foo class and will be using a Foo pointer to delete those derived classes (although as a general rule of thumb, it should be virtual if there are any other virtual members).


这是真的,那么构造函数是否也必须是虚拟的?)

(If that is true, then must the constructor be virtual as well?)

否。构造函数不需要 virtual ,也不能

No. Constructors neither need to be virtual, nor can they.

这篇关于C ++:初始化一个成员指针为null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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