本文介绍了使用与C ++标准允许的成员变量相同的名称为构造函数参数初始化成员变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想出,可以使用与下面示例中所示的相同名称的构造函数参数初始化成员变量。

I figured out that it's possible to initialize the member variables with a constructor argument of the same name as show in the example below.

#include <cstdio>
#include <vector>

class Blah {
    std::vector<int> vec;

public:
    Blah(std::vector<int> vec): vec(vec)
    {}

    void printVec() {

        for(unsigned int i=0; i<vec.size(); i++)
            printf("%i ", vec.at(i));

        printf("\n");
    }
};

int main() {

    std::vector<int> myVector(3);

    myVector.at(0) = 1;
    myVector.at(1) = 2;
    myVector.at(2) = 3;

    Blah blah(myVector);

    blah.printVec();

    return 0;
}

g ++ 4.4带有参数 -Wall -Wextra - pedantic 不提供警告并且工作正常。它也适用于clang ++。我不知道C ++标准是什么说的?

g++ 4.4 with the arguments -Wall -Wextra -pedantic gives no warning and works correctly. It also works with clang++. I wonder what the C++ standard says about it? Is it legal and guaranteed to always work?

推荐答案

是的。这是完全合法的。完全符合标准。

Yes. That is perfectly legal. Fully Standard conformant.

Blah(std::vector<int> vec): vec(vec){}
                             ^   ^
                             |   |
                             |    this is the argument to the constructor
                             this is your member data

§12.6.2/ 7

§12.6.2/7



[Example:
class X {
 int a;
 int b;
 int i;
 int j;
 public:
 const int& r;
  X(int i): r(a), b(i), i(i), j(this->i) {}
                      //^^^^ note this (added by Nawaz)
};



[注意:因为
mem-initializer在构造函数的
范围内求值,所以这个
指针可以在
表达式列表中使用一个mem初始化器
来引用被
初始化的对象。 ]

[Note: because the mem-initializer are evaluated in the scope of the constructor, the this pointer can be used in the expression-list of a mem-initializer to refer to the object being initialized. ]

正如你所看到的,在上面的例子中还有一些值得注意的事情,以及标准本身的注释。

As you can see, there're other interesting thing to note in the above example, and the commentary from the Standard itself.

注意,为什么不接受参数 const reference :

BTW, as side note, why don't you accept the parameter as const reference:

 Blah(const std::vector<int> & vec): vec(vec) {}
      ^^^^const              ^reference

它避免了原始矢量对象的不必要副本。

It avoids unneccessary copy of the original vector object.

这篇关于使用与C ++标准允许的成员变量相同的名称为构造函数参数初始化成员变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 16:44