cpp_Implicit_Conversion - 8BitsCoding/RobotMentor GitHub Wiki

μš°μ„  μ•”μ‹œμ  ν˜•λ³€ν™˜μ€ μ•„λž˜μ™€ 같은 μΌ€μ΄μŠ€κ°€ μžˆλ‹€.

char c = 'A';

int i = c;
char* pc = 0;

void f(int i);
f(c);

dog* pd = new yellowdog();

λͺ¨λ‘ 일반적인 μΌ€μ΄μŠ€λΌ μ„€λͺ…은 μƒλž΅ν•œλ‹€.

μ—¬κΈ°μ„œ λΆ€ν„° μ£Όμ˜ν•΄μ•Όν•  경우λ₯Ό μ„€λͺ…

1. ν•¨μˆ˜μ˜ ν˜ΈμΆœμ‹œ μΌμ–΄λ‚˜λŠ” ν˜•λ³€ν™˜

class dog {
public:
    dog(string name) {m_name = name;}
    // μ—¬κΈ°μ„œ dog(1) μ΄λŸ°μ‹μœΌλ‘œν•΄λ„ μžλ™μœΌλ‘œ ν˜• λ³€ν™˜μ΄ 일어남.
}

ν•΄κ²°μ±…

class dog {
public:
    explicit dog(string name) {m_name = name;}
}

2. ν•΄λ‹Ή 클래슀의 λ¦¬ν„΄ν˜•μ„ μ§€μ •ν•΄μ£Όλ©΄ getν•¨μˆ˜λ₯Ό μ“°μ§€ μ•Šμ•„λ„ λœλ‹€.

class dog {
public:
    operator string () const {return m_name;}
}

void main() {
    string dogname = "Bob";
    dog dog1 = dogname;
    printf("My name is %s \n", dog1);
    // μ΄λŸ°μ‹μœΌλ‘œ μ‚¬μš©μ΄ κ°€λŠ₯
}

μ’€ 더 효율적 μ˜ˆμ‹œλ₯Ό 보자.

class Rational {
public:
    Rational(int numerator = 0, int numerator = 1) : num(numerator), den(dennominator) {}
    int num;
    int den;

    // 이거 μ•ˆλ˜λŠ”λ“― C++11 ν‘œμ€€μΈλ“―
    const Rational operator * (const Rational& lhs, const Rational& rhs) {
        return Rational(lhs.num*rhs.num, lhs.den*rhs.den);
    }
}

int main() {
    Rational r1 = 23;
    // numerator = 23으둜 μ΄ˆκΈ°ν™” 됨 numerator = 1
}