월 24,200원
5개월 할부 시다른 수강생들이 자주 물어보는 질문이 궁금하신가요?
- 미해결홍정모의 따라하며 배우는 C++
이니셜라이저 리스트
int arr[3]={1,2,3} 이런건 이해가 갑니다. auto i1 = {10,20,30} 이나 IntArray int_array {1,2,3,4,5} 이런건 처음보는 경우라 무슨 말인지 초장부터 이해가 안갑니다 ㅠㅠ #include <iostream> #include <cassert> #include <initializer_list> using namespace std; class IntArray{ private: unsigned m_length=0; int *m_data=nullptr; public: IntArray(unsigned length):m_length(length){ m_data=new int[m_length]; } IntArray(const std::initializer_list<int> &list):IntArray(list.size()){ int count=0; for(auto &e : list){ m_data[count]=e; ++count; } } }; int main(int argc, const char * argv[]) { int arr1[5]={1,2,3,4,5}; int *arr2=new int[5]{1,2,3,4,5}; auto il={10,20,30};//initializer list IntArray int_array{1,2,3,4,5}; cout<<int_array<<endl; return 0; }
- 미해결홍정모의 따라하며 배우는 C++
reference사용질문입니다.
5분25초 즈음에 array<int,5>my_arr는 복사를 해야돼서 array가 커지면 시간을 좀 잡아먹는다는 문제가 있다고 하셨는데 5분 35초처럼 대신 array<int,5>& my_arr로 reference로 넣어주면 레퍼런스는 복사를 하지않아서 시간을 잡아먹는 문제가 해결되는것인가요? 그래서 reference를 사용하는것인가요? 감사합니다!
- 미해결홍정모의 따라하며 배우는 C++
copy constructor 안에서 length constructor 호출을 했는데 워닝이 나오는 이유가 궁금합니다.
안녕하세요. visual studio 사용하고 있습니다. 24번째 줄에서 Warning이 뜹니다. C26444 Don't try to declare a local variable with no name (es.84) copy constructor 안에서 length constructor 호출을 했는데 워닝이 나오는 이유가 궁금합니다. #pragma once #include <iostream> class Resource { public: int* m_data = nullptr; unsigned int m_length = 0; public: Resource() { std::cout << "Resource default constructed\n"; } Resource(unsigned int length) { std::cout << "Resource length constructed\n"; this->m_data = new int[length]; this->m_length = length; } Resource(const Resource& res) { std::cout << "Resource copy constructed\n"; // 1. ... Resource(res.m_length); //// 2 ... //this->m_data = new int[res.m_length]; //this->m_length = res.m_length; for (unsigned i = 0; i < m_length; ++i) { m_data[i] = res.m_data[i]; } } ~Resource() { std::cout << "Resource destroyed\n"; if (m_data != nullptr) { delete[] m_data; } } Resource& operator = (Resource& res) { std::cout << "Resource copy assignmnet\n"; if (&res == this) { return *this; } if (this->m_data != nullptr) { delete[] m_data; } m_length = res.m_length; m_data = new int[m_length]; for (unsigned int i = 0; i < m_length; ++i) { m_data[i] = res.m_data[i]; } return *this; } void print() { for (unsigned int i = 0; i < m_length; ++i) { std::cout << m_data[i] << " "; } std::cout << '\n'; } };
- 미해결홍정모의 따라하며 배우는 C++
*this
Digit& operator++ (){ ++m_digit; return *this; } //postfix Digit operator++ (int){ Digit temp(m_digit); ++(*this); return temp; } *this에 대해서 더 알고 싶습니다. 지금 객체에는 멤버변수와 멤버함수가 있고, this는 객체를 포인팅하고 있는 포인터, *this는 멤버 변수가 되는건가요? *this가 객체 자체가 되는거고, *this.m_digit이 말이 되는거 아닌가요? 조금헷갈리네요
- 미해결홍정모의 따라하며 배우는 C++
연습문제 질문입니다
연습문제를 풀던 중 배열은 포인터와 증감연산자를 사용할 수 없다는 것을 발견했습니다. 빨간 줄에서 "expression must be a modifiable lvalue" 라고 뜨는데 배열은 포인터처럼 증감연산자를 사용하지 못하는 이유가 있나요?
- 미해결홍정모의 따라하며 배우는 C++
컴파일에러
main문에 강의상 shuffle하기 위한 그 컴파일 방식?이 컴파일러가 c++17 이후라서 저렇게 추가했는데요! #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; } int getCents() const { return m_cents; } friend std::ostream& operator << (std::ostream &out,const Cents ¢s){ out<<cents.m_cents; return out; } friend bool operator > (const Cents&c1, const Cents&c2){ return c1.m_cents > c2.m_cents; } //std::sort쓸때는 >를 해야지 <를 하면안됨 }; 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; //getCents의 반환형이 참조형이 되야함을 기억할 것! //함수 리턴값은 R-value 입니다. int a = 3; 이라는 식이 있을 때 바로 여기서 3이 R-value 라는 것을 앞에서 배우셨을 겁니다. R-value 메모리는 임시 객체이며 개발자가 임의로 수정할 수 없습니다. 함수 리턴값에 대입을 하고 싶다면 L-value 로서 리턴될 수 있도록 getCetns 의 리턴형을 int & 로 바꿔주세요. } std::shuffle(begin(arr),end(arr),g); for(auto &e : arr){ cout<<e<<" "; }cout<<endl; std::sort(begin(arr),end(arr)); //sort는 크기 비교하는 거라서 >나 <가 필요한데 > 필요하다. for(auto &e : arr){ cout<<e<<" "; }cout<<endl; return 0; } 오류내용:
- 미해결홍정모의 따라하며 배우는 C++
[12:59] std::lock_guard 컴파일 오류
위와 같이 강의 내용 그래로 코드 작성하면 오류가 뜨네요 ㅠ 해당 줄을 std::lock_guard<mutex> lock(mtx); 로수정해서 일단 진행하긴 했는데 강의에서는 왜 오류가 뜨지 않은건가요?C++ 17으로 설정을 바꿔도 그래로 입니다 ㅠ std::scoped_lock도 컴파일오류가 나고 std 맴버로 가지고 있지 않다고 나와서 이후 진행을 못했습니다
- 미해결홍정모의 따라하며 배우는 C++
3:45초
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이라는 에러가 뜨는데.. 이유가 궁금합니다..ㅜㅜ
- 미해결홍정모의 따라하며 배우는 C++
벡터
그 전의 강의들보면 vector선언하실 때 예) vector <int> vec = {1,2,3,4} ; 이런식이였는데요 여기서 vector <int> vec(10); 을 벡터 10개라고 하셨는데 벡터 10개라는의미가 vec =이 vec벡터 1개로 10칸의 배열을 의미한다는 것인가요? 아니면 10개의 벡터가 만들어졌다는 뜻인가요?
- 미해결홍정모의 따라하며 배우는 C++
포인터 자체의 주소 질문입니다.
5분10초쯤에 포인터 자체의 주소, &ptr을 하면 ptr과 당연 다르게 나오는데 이것은 서로 가르키는 주소가 달라서 그런것인가요? ptr은 array의 첫번째 원소의 주소를 나타내는것이고 , &ptr은 주소의 주소를 나타내는것이기에 다른것인가요? 감사합니다!
- 미해결홍정모의 따라하며 배우는 C++
[5:13] 22번줄 main_res = generateResource(); 에서 컴파일러 오류가 나네요 ㅠㅠ
chapter15_03.cpp #include "Timer.h" #include "AutoPtr.h" #include "Resource.h" AutoPtr<Resource> generateResource() { AutoPtr<Resource> res(new Resource(10000000)); return res; } int main() { using namespace std; streambuf* orig_buf = cout.rdbuf(); Timer timer; { AutoPtr<Resource> main_res; main_res = generateResource(); } cout.rdbuf(orig_buf); timer.elapsed(); } Auto.h #pragma once #include <iostream> template<class T> class AutoPtr { private: T* m_ptr = nullptr; public: AutoPtr(T* ptr = nullptr) : m_ptr(ptr) { std::cout << "AutoPtr defalult constructor" << std::endl; } ~AutoPtr() { std::cout << "AutoPtr destructor" << std::endl; if (m_ptr != nullptr) delete m_ptr; } AutoPtr(AutoPtr& a) { std::cout << "AutoPtr copy constructor" << std::endl; //deep copy m_ptr = new T; *m_ptr = *a.m_ptr; } AutoPtr& operator = (AutoPtr& a) { std::cout << "AutoPtr copy assignment" << std::endl; if (&a == this) return *this; if(m_ptr != nullptr) delete m_ptr; //deep copy m_ptr = new T; *m_ptr = *a.m_ptr; return *this; } }; Resource.h #pragma once #include <iostream> class Resource { public: int *m_data = nullptr; unsigned m_length = 0; public: Resource() { std::cout << "Resource default constructed" << std::endl; } Resource(unsigned length) { std::cout << "Resource length constructed" << std::endl; this->m_data = new int[length]; this->m_length = length; } Resource(const Resource& res) { std::cout << "Resource copy constructed" << std::endl; Resource(res.m_length); for (unsigned i = 0; i < m_length; ++i) m_data[i] = res.m_data[i]; } ~Resource() { std::cout << "Resource destoryed" << std::endl; if(m_data != nullptr) delete[] m_data; } Resource& operator = (Resource& res) { std::cout << "Resource copy assignment" << std::endl; if (&res == this) return *this; if (this->m_data != nullptr) delete[] m_data; m_length = res.m_length; m_data = new int[m_length]; for (unsigned i = 0; i < m_length; ++i) m_data[i] = res.m_data[i]; return* this; } void print() { for (unsigned i = 0; i < m_length; ++i) { std::cout << m_data[i] << " "; } std::cout << std::endl; } }; Timer.h #pragma once #include <iostream> #include <vector> #include <algorithm> #include <random> #include <chrono> class Timer { using clock_t = std::chrono::high_resolution_clock; using second_t = std::chrono::duration<double, std::ratio<1>>; std::chrono::time_point<clock_t> start_time = clock_t::now(); public: void elapsed() { std::chrono::time_point<clock_t> end_time = clock_t::now(); std::cout << std::chrono::duration_cast<second_t>(end_time - start_time).count() << std::endl; } }; 위에 코드로 빌드했을때 컴파일 에러가 나고. main()문 안에서 main_res = generateResource(); 줄에 no operator "=" matches these operands 라는 오류가 발생합니다. 오버로딩도 잘되었는데 무슨 문제인지 모르겟네요 ㅠㅠ 함수를 통해서 AutoPtr<Resource>를 받는게 안된다는건지...
- 미해결홍정모의 따라하며 배우는 C++
resize() 이전에 질문드렸던 내용 code 올려드립니다.
#include <iostream> #include <vector> #include <array> #include <initializer_list> class IntArray { int m_length = 0; int* m_data = nullptr; public: IntArray(int length_in) : m_length(length_in) { m_data = new int[m_length]; } IntArray(const std::initializer_list<int>& list) : IntArray(list.size()) { initialize(list); } ~IntArray() { delete[] m_data; } void initialize(const std::initializer_list<int>& list) { int count = 0; for (auto& ele : list) { m_data[count] = ele; ++count; } } void reset() { m_length = 0; if (m_data != nullptr) { delete[] m_data; m_data = nullptr; } } void resize(const int& size) { int pre_length = m_length; m_length = size; if (m_data != nullptr) { int* temp = new int[pre_length]; for (int i = 0; i < pre_length; i++) temp[i] = m_data[i]; delete[] m_data; m_data = new int[m_length]; //for (int i = 0; i < m_length; i++) for (int i = 0; i < pre_length; i++) { m_data[i] = temp[i]; //if (i <= pre_length) m_data[i] = temp[i]; //else m_data[i] = 0; if (i == size - 1) break; //size가 작아질 경우 } delete[] temp; } else m_data = new int[m_length]; } void insertBefore(const int& value, const int& ix) { resize(m_length + 1); for (int i = 0; i < m_length; i++) { if (m_data[i] == ix) { for (int j = m_length - 1; j > i; j--) m_data[j + 1] = m_data[j]; m_data[i+1] = value; break; } } } void remove(const int& ix) { for (int i = 0; i < m_length; i++) { if (m_data[i] == ix) { for (int j = i; j < m_length - 1; j++) m_data[j] = m_data[j + 1]; resize(m_length - 1); break; } } } void push_back(const int& value) { resize(m_length + 1); m_data[m_length -1] = value; } friend std::ostream& operator << (std::ostream& out, const IntArray& arr) { for (int i = 0; i < arr.m_length; i++) out << arr.m_data[i] << " "; return out; } }; int main() { IntArray my_arr{ 1,3,5,7,9 }; std::cout << my_arr << std::endl; my_arr.insertBefore(10,1); std::cout << my_arr << std::endl; my_arr.remove(3); std::cout << my_arr << std::endl; my_arr.push_back(13); std::cout << my_arr << std::endl; std::vector<int> int_vec; std::array<int, 10> int_arr; return 0; } 웨에 코드입니다 사이즈를 크게 바꾸면서 빈자리에는 초기화를 안해주었는데 그때문에 문제가 생기는게 아닐까 했지만 나이라고 하셔서 코드올려드립니다. 주석처리 된대로 바꾸면 잘 동작합니다 ㅠ 아래 인터넷 컴파일러 주소 올려드립니다. http://tpcg.io/yjKoNFmS
- 미해결홍정모의 따라하며 배우는 C++
print() defintion을 cpp파일로 옮긴 후 실행했을 때 Link 에러나 발생합니다
강의와 똑같이 진행했다고 생각했는데 어디서 문제가 발생했는지 모르겠네요.. 온라인 컴파일러로 실행시켰을때도 아래와 같은 애러가 뜨네요 ㅠㅠ Storage.cpp:(.text+0x0): multiple definition of `Storage::print()' /tmp/ccGcctjd.o:main.cpp:(.text+0x0): first defined here collect2: error: ld returned 1 exit status 제가 작성한 코드 아래에 주소 남깁니다 ㅠ https://onlinegdb.com/AnTPCcmZC
- 미해결홍정모의 따라하며 배우는 C++
함수의 매개변수에 배열을 넣을 때
#include <iostream> #include <vector> using namespace std; void func1(int arr[]) { arr[0] = 7; } void func2(vector<int> v) { v[10] = 7; } int main() { int arr[] = {0, 0}; vector<int> v(100); func1(arr); func2(v); cout << arr[0] << " " << v[10]; return 0; } -> 7 0 매개변수에 배열이 들어가면 배열의 주소가 복사되어 들어갈텐데 func1의 경우 래퍼런스를 사용한 것도 아닌데 func1 내에서의 arr과 main에서 arr의 주소가 같은지 모르겠습니다. func2의 경우는 func2 내부와 main에서 v의 주소가 다름을 확인했습니다. 주소가 그대로 매개변수에 들어가 함수에서 바뀐 값이 출력되었는데 어떤 이유로 arr의 주소가 공유가 되는것인가요?
- 해결됨홍정모의 따라하며 배우는 C++
[7:00] 무한루프 안에서 소멸자 호출 관련 질문합니다
7분대부터 나오는 예제에서 무한루프 안에 객체를 생성 하는데요 main 함수가 종료되지 않음에도 소멸자가 호출되는것을 볼 수 있습니다. 알아낸것이 n번째 루프에서 생성된 객체는 n+1 루프에서 소멸자가 호출이 되더라구요 왜 이렇게 소멸자가 호출이 되는지 알 수 있을까요??
- 미해결홍정모의 따라하며 배우는 C++
resize() 함수 구현중 질문이 있습니다
resize() 함수 구현중에 size가 증가할때 증가된 변수 자리에는 아무것도 안넣었는데 그러면 다음에 Delete[] 할때 런타임에러가 발생하더라고요 빈자리를 0으로 초기화도록 바꾸니깐 에러가 없어졌는데 포인터에 인트형 배열 메모리를 할당하고 꼭 초기화를 다 해주어야 Delete[] 가능한건가요?
- 미해결홍정모의 따라하며 배우는 C++
const 관련 질문입니다.
여러 const 관련 강의를 통해 개념을 잡아가는 중인데 int * const 를 쓰면 포인터자체가 상수화가 돼서 포인터 주소값 변경이 안돼야 하는데 이 함수에서 Getptr 에서 반환값으로 포인터에 래퍼런스 값을 돌려주는데 int *& const 이렇게 돌려줍니다 그러면 main 함수에서 ptr의 주소값이 변경되지 않아야 할 꺼 같은데 왜 변경되는건지 궁금합니다 리턴값 선언에서 int *& 의 정확한 역할이 무엇인지 궁금합니다
- 미해결홍정모의 따라하며 배우는 C++
강의랑 똑같은 입력
#include <iostream> using namespace std; class fruit{ public: enum class fruitType{ //enum class apple,banana,cherry, }; private: fruitType m_type; public: fruit(fruitType type):m_type(type){} fruitType getType(){ //fruitType형을 반환한다 return m_type; } }; int main(int argc, const char * argv[]) { fruit::fruitType Apple(fruit::fruitType::apple); if(Apple.getType() == fruit::fruitType::apple){ cout<<"Apple!"<<endl; } return 0; } main문의 Apple.getType()에서 fruit::fruitType is not a structure or union이라는 오류메시지가 뜹니다 ㅠ memb ㄴㅁㅇㄹer reference base type 'fruit::fruitType' is not a structure or unioㅁㄴㅇㄹ
- 미해결홍정모의 따라하며 배우는 C++
참조자 반환형오류
#include <iostream> using namespace std; class Cents{ private: int m_cents; public: Cents(const int& cents):m_cents(cents){} int getCents() const { return m_cents; } }; //반환형이 참조자일 시 오류 Cents& addCents(const Cents &a,const Cents &b){ return Cents( a.getCents()+b.getCents() ); //익명객체 사용 } int main(int argc, const char * argv[]) { Cents a(5); Cents b(7); cout<<addCents(a, b).getCents()<<endl; return 0; } return으로 Cents객체를 반환하는데 값의 복사형식이 아닌 그 자체를 반환하겠다인 의미잖아요? 반환형이 Cents면 ok인데 Cents&하는 순간 return문에서 오류가 납니다. 이유가 무엇인가요?
- 미해결홍정모의 따라하며 배우는 C++
클래스 설계
안녕하세요. 12.7 강의를 보고 클래스 설계에 관하여 질문드립니다. 추상클래스 예제로 Animal 을 이용해 예제를 보여주셨는데요. 인터페이스 클래스로 구성하면 string을 새로운 클래스에다가 넣고, IAniamal 클래스에 speak() 함수만 넣어놓고 구성할 수 있자나요. - 인터페이스 + 상속 이용 - 추상클래스를 이용한 설계 이런식으로 그렇다면, 추상클래스로 설계하는 것이 좋을까요? 인터페이스 형식으로 설계하는 것이 좋을까요??