【发布时间】:2017-10-25 03:07:39
【问题描述】:
我想创建一个 MPSList 类,其中构造函数具有与之关联的显式关键字。
以下是最简单的代码:
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;
};
创建 MPSList 类对象的 CPP 文件。
#include <iostream>
#include "MPSList.hpp"
int main() {
double n = 10.9;
MPSList mps(n);
}
在编译上述 CPP 文件时,我曾预料会在初始化对象时看到错误。当我传递一个 double 而构造函数明确地期望一个 int 时。
编译命令:
g++ -std=c++14 -I../include test.cpp
./a.out
【问题讨论】:
-
这不是
explicit说明符的意义所在 - 它只会阻止 converting constructors,例如:在您的情况下是MPSList mps = n; -
也许在您的示例中使用 delete 关键字来删除
double和float版本的构造函数?我想知道它是否可行,但请试一试!
标签: c++ explicit explicit-constructor