강의

멘토링

로드맵

인프런 커뮤니티 질문&답변

khb4435님의 프로필 이미지
khb4435

작성한 질문수

홍정모의 따라하며 배우는 C++

9.4 비교 연산자 오버로딩 하기

3:45초

작성

·

324

1

for(unsigned i =0 ; i<20 ; ++i)

이게 가능한 문법인가요?

unsigned int i = 0 이게 맞는거 아닌가요? 컴파일까지 문제없이 된 것으로 보아 맞는것 같은데 그냥 unsigned면 int가 생략되는건가요?

#include <iostream>

#include <vector>

#include <algorithm>

#include <random>

using namespace std;

class Cents{

private:

    int m_cents;

public:

    Cents(const int &cents):m_cents(cents){}

    int getCents() { return m_cents; }

    friend std::ostream& operator << (std::ostream &out,const Cents &cents){

        out<<cents.m_cents;

        return out;

    }

};

int main(int argc, const char * argv[]) {

    std::random_device rd;

    std::mt19937 g(rd());

    vector<Cents>arr(20); //arr이름으로 된 Cents형 20개

    for(unsigned i = 0 ; i<20 ; ++i){

        arr[i].getCents() = i;

    }

    std::shuffle(begin(arr),end(arr),g);

    return 0;

}

한가지 더 질문을 드리자면..제가 하면 arr[i].getCents() = i;여기서 Expression is not assignable이라는 에러가 뜨는데.. 이유가 궁금합니다..ㅜㅜ

퀴즈

66%나 틀려요. 한번 도전해보세요!

사용자 정의 타입에 대해 연산자 오버로딩을 하는 주된 목적은 무엇일까요?

코드 실행 속도를 빠르게 하기 위해

사용자 정의 타입을 내장 타입처럼 자연스럽게 사용하기 위해

객체의 메모리 관리를 자동화하기 위해

클래스의 상속 관계를 정의하기 위해

답변 1

1

안녕하세요~

1. int 생략 가능합니다. i 에 커서 대보면 unsigned int i 라고 뜨고 잘 인식 하네요!. C++ allows a shorthand notation for declaring unsigned, short, or long integers. You can simply use the word unsigned, short, or long, without int

https://www.tutorialspoint.com/cplusplus/cpp_modifier_types.htm

2. 함수 리턴값은 R-value 입니다. int a = 3; 이라는 식이 있을 때 바로 여기서 3이 R-value 라는 것을 앞에서 배우셨을 겁니다. R-value 메모리는 임시 객체이며 개발자가 임의로 수정할 수 없습니다. 함수 리턴값에 대입을 하고 싶다면 L-value 로서 리턴될 수 있도록 getCetns 의 리턴형을 int & 로 바꿔주세요.

khb4435님의 프로필 이미지
khb4435
질문자

안녕하세요. 매번 질문할 때 마다 정말 많은 것을 배웁니다 감사드립니다..^^

khb4435님의 프로필 이미지
khb4435

작성한 질문수

질문하기