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
}