1

I wanted to create a class MPSList where constructor has an explicit keyword associated with it.

Following is the bare minimal code:

class MPSList {                                                                           
public:                                                                                   
    explicit MPSList(int n) : n_(n) {                                                     
        mpsL.resize(n_, std::vector<MPSNode>{});                                          
        std::cout << mpsL.size() << std::endl;                                            
     }

private:
    struct MPSNode {                                                                      
        double s_;                                                                        
    };

    std::vector<std::vector<MPSNode>> mpsL;
    int n_ = -1;
}; 

CPP file that creates the object of MPSList class.

#include <iostream>

#include "MPSList.hpp"

int main() {
    double n = 10.9;
    MPSList mps(n);    
}

On compiling the above CPP file, I had expected to see an error in initializing the object. As I am passing a double whereas the constructor is explicitly expecting an int.

Command to compile:

g++ -std=c++14 -I../include test.cpp 
./a.out
4

1 回答 1

6

显式阻止编译器执行以下操作:

void fn(MPSNode x); // or void fn(const MPSNode& x)
fn(3.0);

如果您不使用explicit,上面的代码段将编译,并且调用的行fn等效于:

fn(MPSNode(3.0));

这是从到的隐式转换。缩小转换与它的关系相对较小。doubleMPSNode

但是,您会发现以下内容无法编译:

MPSList mps{n};

如果您想解决此类问题,请使用统一初始化语法。

于 2017-05-24T16:39:27.320 回答