2015-09-09 6 views
1

я нашел следующий код на cppreference.com (я смотрел вверх, что означало explicit ключевого слова.)Что означает использование ключевого слова `operator`?

struct A 
{ 
    A(int) {} // converting constructor 
    A(int, int) {} // converting constructor (C++11) 
    operator int() const { return 0; } 
}; 

На третьей строке определения структуры есть строка: operator int() const { return 0; }

Я не уверен, что делает эта линия. Какой оператор перегружен, это int?

Я посмотрел here, чтобы попытаться понять это сам, но я все еще царапаю себе голову.

+1

В ссылке вы публикуемую вы видите 'оператор типа \t (2)', и если вы будете следовать второй ссылке вы получите в HTTP: //en.cppreference.com/w/cpp/language/cast_operator. –

+0

Проверьте http://stackoverflow.com/questions/28307887/c-type-cast-operator-overloading-and-implicit-conversions?s=3|2.4106 –

+0

@FelixKling, не уверенный, как я пропустил это. Благодаря! – Stephen

ответ

3

Это Определяемый пользователем оператор преобразования

http://en.cppreference.com/w/cpp/language/cast_operator

struct X { 
    //implicit conversion 
    operator int() const { return 7; } 

    // explicit conversion 
    explicit operator int*() const { return nullptr; } 

// Error: array operator not allowed in conversion-type-id 
// operator int(*)[3]() const { return nullptr; } 
    using arr_t = int[3]; 
    operator arr_t*() const { return nullptr; } // OK if done through typedef 
// operator arr_t() const; // Error: conversion to array not allowed in any case 
}; 

int main() 
{ 
    X x; 

    int n = static_cast<int>(x); // OK: sets n to 7 
    int m = x;      // OK: sets m to 7 

    int* p = static_cast<int*>(x); // OK: sets p to null 
// int* q = x; // Error: no implicit conversion 

    int (*pa)[3] = x; // OK 
} 
Смежные вопросы