인프런 커뮤니티 질문&답변
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 ¢s):m_cents(cents){}
int getCents() { return m_cents; }
friend std::ostream& operator << (std::ostream &out,const Cents ¢s){
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이라는 에러가 뜨는데.. 이유가 궁금합니다..ㅜㅜ
답변 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 & 로 바꿔주세요.






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