C++方法声明问题

Jac*_*sen 4 c++ methods syntax declaration

我在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;  
};  
Run Code Online (Sandbox Code Playgroud)

我的问题是:m_sFilename第一行发生了什么?我猜它被设置为NULL,但这样做的重点是什么.做同样的事情是这样的:

Image::Image( int width, int height, int depth )  
{  
    m_sFileName(0);  
...  
}
Run Code Online (Sandbox Code Playgroud)

GMa*_*ckG 11

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

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

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

因此,str构建,然后分配.更好的是:

class Foo
{
 public:
    Foo()
    : str("String.")
    {
    }
private:
    std::string str;
};
Run Code Online (Sandbox Code Playgroud)

这样str就直接构建了.这对你的情况没有影响,因为指针没有构造函数.

通常认为在构造函数中使用初始化列表而不是运行代码是一种好习惯.在初始化列表应该用于初始化,构造函数应该用于运行的代码.

另外,为什么要使用指向字符串的指针?如果你想要一个字符串,使用一个字符串; 不是指向字符串的指针.有可能,你真的想要一个字符串.


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

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

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.
    {
        /* ... */
    }
};
Run Code Online (Sandbox Code Playgroud)

或者不变的成员:

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

或参考:

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;
};
Run Code Online (Sandbox Code Playgroud)

  • 这是一个很好的答案!还要注意有时初始化列表是唯一的方法,因为不能分配const成员变量和引用...所以在这种情况下你必须使用初始化列表. (2认同)