TIL/[C++ 프로그래밍} TIL

TIL 22.06.08 (시험에 나올만한..?)

맹찬 2022. 6. 9. 08:56
std::ostream& operator<<(std::ostream& os, const T& obj){
return os;
}

여기서 os는 객체의 이름을 쓰는게 아니라, parameter를 써야 하므로, cout을 쓰면 틀림

std::istream& operator>>(std::istream& is, T& obj){
return is;
}

멤버함수

Complex Complex::operator+(const Complex& c){
    Complex result(re + c.re, im + c.im);
    return result;
}
// 이게 맞음 (result를 리턴해야해)

틀린 예시 :

Complex Complex::operator+(const Complex& c){
    re += c.re;
    im += c.im;
    return *this; // 이렇게 하면 x 값이 바뀌게 되니까 안됨

const 선언 안했는데 왜 에러가 날까

Complex& Complex::operator=(const Complex& c){ // 이렇게 해야 에러가 안남
    re = c.re; im = c.im;
    return *this;


//실행문에서
Complex x(2,3);
Complex y(-1, -3);

z = x + y // 얘를 하게 되면 x + y 의 임시 변수가 const 선언을 하면서 나와서
// 에러가 나게 됨 .