[열혈 c++ 프로그래밍] ch6

hyng·2023년 3월 15일
0

열혈 c++ 프로그래밍을 보고 요약정리합니다.

6-1 const와 관련해서 아직 못다한 이야기

  • const 객체와 const 객체의 특성
    • const객체는 const로 선언된 함수만 호출할 수 있다.

6-2 클래스와 함수에 대한 friend 선언

  • A클래스가 B클래스를 대상으로 friend 선언을 하면, B 클래스는 A 클래스의 private 멤버에 직접 접근이 가능하다.
  • 단 A 클래스도 B 클래스의 private 멤버에 직접 접근이 가능하려면 B 클래스가 A 클래스를 대상으로 friend 선언을 해줘야 한다.
    class Boy
    {
    	private:
    		int height;
    		friend class Girl;
      public:
    		Boy(int len) : height(len)
    		{}
        .....
    };
    
    class Girl
    {
    	private:
    		char phNum[20];
    	public:
    		Girl(char *num)
    		{
    			 strcpy(phNum, num);
    		}
    		void ShowYourFriendInfo(Boy &frn)
    		{
           cout << "His height: " << frn.height << endl;
    		}
    
    };
  • 전역함수 멤버 함수 또한 friend 선언이 가능하다.

6-3 c++에서의 static

  • static 멤버 변수
    • 이 변수는 객체 외부에 있지만 객체에게 멤버변수처럼 접근할 수 있는 권한이 있는것

    • static 멤버 변수의 초기화 방법

      int SoSimple::simObjCnt = 0;

      멤버 변수 선언과 동시에 값을 초기화하는게 더 낫지 않을까 했는데 그렇게는 허용이 안된다.
      static int simObjCnt = 0;

  • static 멤버 함수
    • static 멤버 함수는 static 멤버 변수, static 멤버 함수에만 접근할 수 있다.
  • const static 멤버
    • const 멤버 변수(상수)의 초기화는 이니셜라이저를 통해야만 한다.
    • 그러나 const static으로 선언되는 멤버 변수(상수)는 선언과 동시에 초기화가 가능하다.
      const static int RUSSIA = 1707540;
      CountryArea::RUCCIA;

6-4 OOP 단계별 프로젝트

  • Account 클래스의 멤버 함수 중 일부를 const로 선언
    class Account{
    private:
        int id;
        int balance;
        char *name;
        Account(int id, int balance, char *name) {
            this->id = id;
            this->balance = balance;
            this->name = new char[::strlen(name) + 1];
            ::strcpy(this->name, name);
        }
    public:
        Account() {
    
        }
    
        Account(const Account & account)
        {
            this->id = account.id;
            this->balance = account.balance;
            this->name = new char[strlen(account.name) + 1];
            strcpy(this->name, account.name);
        }
        static Account Of(int _id, int _balance, char* _name) {
            return Account(_id, _balance, _name);
        }
        bool IsSame(int id) {
            return this->id == id;
        }
        void Deposit(int money) {
            this->balance += money;
        }
    
        void Withdraw(int money) {
            if (this->balance < money) {
                cout << "잔액부족\n";
                return;
            }
            this->balance -= money;
            cout << "출금완료\n";
        }
        void ShowInfo() const {
            cout << "계좌ID: " << id << "\n";
            cout << "이 름: " << name << "\n";
            cout << "잔 액: " << balance << "\n";
        }
        Account* Copy() {
            return new Account(this->id, this->balance, this->name);
        }
    };
profile
공부하고 알게 된 내용을 기록하는 블로그

0개의 댓글