3

完整的代码。稍后指定的行。

#include <iostream>
#include <string>

using namespace std;

class X
{
    private:

    int i;
    float f;
    char c;

    public:

    X(int first=1, float second=2.0, char third='a') : i(first) , f(second) , c(third) { } 
    void print() { cout << i << " " << f << " " << c << endl;}

};


int main()
{
    X var1;
    var1.print();

    return 0;
}

这条线上到底发生了什么:

X(int first=1, float second=2.0, char third='a') : i(first) , f(second) , c(third) { }

据我所知(可能是错误的),我们首先声明对象,第二个和第三个类型(类)X。我们在声明期间初始化它们。结肠后发生了什么?到底是怎么回事?

4

4 回答 4

3

这条线上到底发生了什么:

X(int first=1, float second=2.0, char third='a') 
: i(first) , f(second) , c(third) { 
}

它是一个构造函数,它接受 3 个具有默认值的参数。

这部分: i(first) , f(second) , c(third)称为member initializer list. 成员初始值设定项列表由逗号分隔的初始值设定项列表组成,前面有一个冒号。它位于参数列表的右括号之后和函数体的左括号之前。

只有构造函数可以使用这个初始化列表语法。const 类成员必须在成员初始化器中初始化。

于 2012-11-28T22:25:17.547 回答
2

The stuff in the parenthesis are default values for the arguments to the constructor, and the stuff after the colon initializes those items after the colon.

The colon notation is most commonly used to invoke the constructors of other objects the class uses.

于 2012-11-28T21:38:05.390 回答
2

您有具有三个字段的 X 类:i、f、c。您已经定义了具有三个默认参数的构造函数 - 当此构造函数调用的字段使用参数初始化时(传递给构造函数或默认值)。就像是:

X (int first=1, float second=2.0, char third='a')
{
   i = first;
   f = second;
   c = third;
}

您的行只是初始化字段的另一种方式,通常它们是相等的(继承存在一些差异)。

在您的主代码中,您正在创建一个var1X 类型的局部变量,因此调用了构造函数。您不传递任何参数,因此使用默认值。

结果,您有一个X 类型的本地对象,使用构造函数中列出的默认值进行了初始化。

于 2012-11-28T21:52:05.647 回答
1
X(int first=1, float second=2.0, char third='a') : i(first) , f(second) , c(third) { }

这是 X 的构造函数。共有三个参数,每个参数都有一个默认值,因此可以以不同的方式调用它

X myX;
X myX(first);
X myX(first, second);
X myX(first, second, third);

论据之后的部分

: i(first) , f(second) , c(third)

i,fc成员的初始化器。如果可能的话,这种初始化风格优于函数体中的初始化,并且如果成员是常量类型,则需要这种风格。

然后构造函数有一个空体{}

于 2012-11-28T21:46:24.627 回答