C ++方法声明问题 [英] C++ method declaration question

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

问题描述

我在Image.cpp中有一些代码:

I have some code in Image.cpp:

Image::Image( int width, int height, int depth ) : m_sFileName(0)  
{  
...  
}  

and in Image.h:  
class Image: public DrawAble, public RenderAble  
{  
...  
private :  
    std::string *m_sFileName;  
};

我的问题是: m_sFilename 在第一行?我想它被设置为NULL,但是这样做的意义是什么。是否可以这样做:

My question is: what is happening with m_sFilename in the first line? I guess it is set to NULL but what's the point of doing it that way. Would it be the same to do:

Image::Image( int width, int height, int depth )  
{  
    m_sFileName(0);  
...  
}


推荐答案

第一个使用所谓的初始化列表

当您输入构造函数的主体时,所有的类成员必须已经被构造(所以它们可以被使用)。所以如果你有这个:

When you enter the body of the constructor, all of the classes members must have been constructed (so they can be used). So if you have this:

class Foo
{
public:
    Foo()
    : str() // this is implicit
    {
        str = "String.";
    }
private:
    std::string str;
};

因此,构建了 str 。更好的应该是:

So, str gets constructed, then assigned. Better would have been:

class Foo
{
 public:
    Foo()
    : str("String.")
    {
    }
private:
    std::string str;
};

这样可以直接构造 str 这在你的情况下没有什么区别,因为指针没有构造函数。

So that str gets directly constructed. This does not make a difference in your case because pointers have no constructor.

在构造函数中运行代码时使用初始化列表是一个好习惯。

It is generally considered good practice to use an initialization list over running code in the constructor. The initialization list should be used for initializing, the constructor should be used for running code.

此外,为什么要使用初始化列表来初始化使用指针字符串?如果你想要一个字符串,使用一个字符串;不是指向字符串的指针。

Also, why use a pointer to string? If you want a string, use a string; not a pointer to string. Chances are, you actually want a string.


有关初始化器列表的更多信息:

More about initializer lists:

初始化器列表具有更多的用途,而不仅仅是初始化类的成员。它们可以用来将参数传递给基本构造函数:

Initializer lists have more uses than just initializing members of the class. They can be used to pass arguments into base constructors:

class Foo
{
public:
    Foo(int i) { /* ... */ }
}

class Bar
    : public Foo
{
public:
    Bar()
    : Foo(2) // pass 2 into Foo's constructor.
             // There is no other way of doing this.
    {
        /* ... */
    }
};

或常数成员:

class Foo
{
public:
    Foo()
    : pi(3.1415f)
    {
        pi = 3.1415f; // will not work, pi is const.
    }
private:
    const float pi;
};

或参考资料:

class Foo
{
public:
    Foo(int& i)
    : intRef(i) // intRef refers to the i passed into this constructor
    {
        intRef = i; // does *not* set intRef to refer to i!
                    // rather, it sets i as the value of
                    // the int intRef refers to.
    }
private:
    int &intRef;
};

这篇关于C ++方法声明问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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