본문 바로가기
반응형

01.Bit 단기/C++53

26_has a 객체초기화 #include using namespace std; /* has a(소유) 소유 개체 초기화 포함개체의 생성은 암시적으로 인자가 없는 기본생성자를 호출시킨다. 포함개체 생성자의 호출을 명시적으로 제어할수 있다. 생성자 콜론초기화 영역에서 아래와 같이 호출 포함개체의 이름(인자전달, .,..) */ class A { string msg; char ch; public: A() { cout 2018. 5. 3.
25_has a 객체생성순서 #include using namespace std; /* has a(소유) 만약 B 개체가 A개체를 소유하고 있다면 B개체 생성시 A개체도 생성된다. 누가먼저? 포함개체가 먼저 생성된다. */ class A { public: A() { cout 2018. 5. 3.
24_상수멤버함수 #include using namespace std; //상수화 맴버 class MyMath { int num; public: //상수맴버함수 //맴버변수 값을 변경하지 않겠다.. //일반맴버함수의 호출도 불가한다. //why? 일반맴버함수가 맴버변수값 수정할수있기때문 void foo(int n) const { // num++; //error n++; //ok. // woo(); //error. } void woo() { num++; //맴버변수값 수정..접근 가능 } }; int main() { MyMath m; //생성과 동시에 초기화 int num = 0; //생성후 대입연산을 이용한 초기화 int num1; num1 = 0; return 0; } 2018. 5. 3.
23_상수멤버변수 #include using namespace std; //상수화 맴버 //맴버변수를 상수화 할수있다. //문법적으로 반드시 초기화가 필요하다. //생성자는 콜론초기화 문법을 통해 생성과 동시에 //맴버변수를 초기화 할수있는 문법을 제공한다. //가능하면 일반변수도 콜론초기화영역에서 //초기화하는것이 효율적이다. class MyMath { int num; const int c_num; //상수화 맴버 public: //콜론초기화 MyMath() : c_num(0) { num = 0; // c_num = 0; } }; int main() { MyMath m; //생성과 동시에 초기화 int num = 0; //생성후 대입연산을 이용한 초기화 int num1; num1 = 0; return 0; } 2018. 5. 3.
22_static 멤버함수 #include using namespace std; //정적맴버함수 //정적맴버 : 객체 없이 접근 가능..... // 당연히 일반 맴버 변수/함수 호출 불가 class MyMath { int a; static int b; public: static int Max(int n1, int n2) { // a++; //일반맴버변수or함수사용불가.. b++; //가능.. return n1 > n2 ? n1 : n2; } }; int MyMath::b = 0; int main() { //정적맴버함수 사용1 //객체 없이, 클래스명으로 접근 가능 cout 2018. 5. 3.
21_static 멤버변수 #include using namespace std; //정적맴버변수 //객체 생성과 무관하다. //전역정적공간에 저장되고 //모든 객체가 그 공간을 공유해서 사용하게 된다. class Account { string name; int id; int balance; static int g_count; //정적맴버변수 public: Account(string _name, int _id, int _balance) : name(_name), id(_id), balance(_balance) { g_count++; Info(); } ~Account() { } public: void Info() { cout 2018. 5. 3.
20_개체 생성과 소멸시점 #include using namespace std; class Stu { public: Stu() { cout 2018. 4. 30.
19_heap객체생성 // 동적메모리(힙(heap) 메모리 사용) #include using namespace std; class Member { public: string name; int age; public: Member() { name = ""; age = 0; } Member(string _name, int _age) { name = _name; age = _age; } }; int main() { //객체 생성시 자동으로 생성자 호출... Member m1; Member m2("홍길동", 10); //pm 과 pm1 //공통점 : Member 타입의 주소를 가진다. //차이점 : pm은 스택에 생성된 객체의 주소 // pm1은 힙에 생성된 메모리의 주소 // pm2는 힙에 생성된 객체의 주소 //결론은 힙에 객체를.. 2018. 4. 30.
18_heap메모리 사용(C/C++ 비교) #include using namespace std; int main() { int n; int *p = &n; //C언어 기반 // malloc // 사용할 크기(byte)를 전달하면 // 힙메모리에 해당 크기의 메모리를 동적으로 // 생성하고, 해당 주소를 반환해준다. // 단, 실패할 경우 NULL을 반환한다. int *p1 = (int*)malloc(sizeof(int)); *p1 = 10; cout 2018. 4. 30.
반응형