zoukankan      html  css  js  c++  java
  • c++ vector能否在类定义中圆括号/大括号初始化

    Why can in-class initializers only use = or {}?
    In-class initializers (C++11 feature) must be enclosed in curly braces or follow a = sign. They may not be specified inside parenthesis.

    What is the reason for this?

    I am not 100% positive about this, but this might be to prevent a syntax ambiguity. For example, consider the following class:

    class BadTimes {
        struct Overloaded;
        int Overloaded;            // Legal, but a very strange idea.

        int confusing(Overloaded); // <-- This line
    };

    What does the indicated line mean? As written, this is a declaration of a member function named confusing that accepts as a parameter an object of type Overloaded (whose name isn't specified in the function declaration) and returns an int. If C++11 were to allow initializers to use parentheses, this would be ambiguous, because it could also be a definition of a member of type int named confusing that is initialized to the value of the data member Overloaded. (This is related to the current issue with the Most Vexing Parse.)

    By requiring curly braces, this ambiguity is removed:

    class BadTimes {
        struct Overloaded;
        int Overloaded;            // Legal, but a very strange idea.

        int confusing{Overloaded}; // <-- This line
    };

    Now, it's clear that confusing is actually an int initialized to the value of Overloaded, because there's no way to read it as a function declaration.

    Hope this helps!



    You cannot do this:

    vector<string> name(5); //error in these 2 lines
    vector<int> val(5,0);

    in a class outside of a method.

    You can initialize the data members at the point of declaration, but not with () brackets:

    class Foo {
        vector<string> name = vector<string>(5);
        vector<int> val{vector<int>(5,0)};
    };

    Before C++11, you need to declare them first, then initialize them e.g in a contructor

    class Foo {
        vector<string> name;
        vector<int> val;
     public:
      Foo() : name(5), val(5,0) {}
    };


  • 相关阅读:
    Android之SurfaceView学习(一)
    AS3的加载机制(带例子) 转载
    Timer与TimerTask的用法
    A*寻路初探 GameDev.net (转载)
    解决在Sql Server2005查询分析器中读取Excel表出现的一些问题
    svn更改用户问题
    MVC4 WEBAPI初探
    使用WORD2013发布blog
    一个IIS中可否支持两个版本的Freamwork
    web打印也能分页
  • 原文地址:https://www.cnblogs.com/CreatorKou/p/8667337.html
Copyright © 2011-2022 走看看