LoginSignup
0
0

More than 1 year has passed since last update.

c++ explicit指定子

Posted at

役割

C++ explicit暗黙の型変換を防ぐため

環境

Visual Studio 2019 (v142)

#include <iostream>
using namespace std;

class Point
{
public:
    int x, y;
    Point(int x = 0, int y = 0)
        : x(x), y(y)
    {
    }
};

void displayPoint(const Point& p)
{
    cout << "(" << p.x << ","
        << p.y << ")" << endl;
}

int main()
{
    displayPoint(1);// Ok
    Point p = 1; // OK
}

main関数のdisplayPoint(1)で暗黙の型変換が発生

#include <iostream>
using namespace std;

class Point
{
public:
    int x, y;
    explicit Point(int x = 0, int y = 0)
        : x(x), y(y)
    {
    }
};

void displayPoint(const Point& p)
{
    cout << "(" << p.x << ","
        << p.y << ")" << endl;
}

int main()
{
    displayPoint(1);
    Point p = 1;
}

ビルド時以下のエラーメッセージが表示され

error C2664: 'void displayPoint(const Point &)': 引数 1 を 'int' から 'const Point &' へ変換できません。
message : 理由: 'int' から 'const Point' へは変換できません。
message : class 'Point' のコンストラクターが 'explicit' と宣言されています。
message : 'displayPoint' の宣言を確認してください
error C2440: '初期化中': 'int' から 'Point' に変換できません。
message : class 'Point' のコンストラクターが 'explicit' と宣言されています。

変更

C++ 11前コンストラクタ一つ引数
C++ 11以後に2個以上引数を取るコンストラクタ

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0