チラシの裏は意外と白くない

最近忘れっぽくなったので調べたことをチラシの裏に書きます

クラスに関して①:基本的なところ

クラスの話。これも今更感があるけどメモ。

構成

基本の基本から。とりあえず”人”クラスで、年齢・身長・体重をprivateに、これらをセットする関数とゲットする関数を用意。

ファイル 内容
man.h CManクラスの定義
man.cpp CManの実装
main.cpp CManの利用

ソースコード

man.h

#ifndef __MAN_H__
#define __MAN_H__

// クラス宣言
class CMan
{
    public:
        void set_age(int age);
        void set_height(int height);
        void set_weight(int weight);
        int get_age();
        int get_height();
        int get_weight();
    private:
        int m_age;
        int m_height;
        int m_weight;
};

#endif // __MAN_H__

man.cpp

#include "man.h"

void CMan::set_age(int age){
    m_age = age;
}

void CMan::set_height(int height){
    m_height = height;
}

void CMan::set_weight(int weight){
    m_weight = weight;
}

int CMan::get_age(){
    return m_age;
}

int CMan::get_height(){
    return m_height;
}

int CMan::get_weight(){
    return m_weight;
}

main.cpp

#include <iostream>
#include "man.h"

using namespace std;

int main(){
    CMan suzuki;
    suzuki.set_age(40);
    cout << "age of suzuki is " << suzuki.get_age() << endl;
    cout << "height of suzuki is " << suzuki.get_height() << endl;

    CMan ueda;
    ueda.set_age(50);
    cout << "age of ueda   is " << ueda.get_age() << endl;

    return 0;
}

実行結果

$ g++ main.cpp man.cpp
$ ./a.out 
age of suzuki is 40
height of suzuki is 0
age of ueda   is 50

setしたageは読めているが、setしていない身長は初期値が呼ばれる。この場合は0。

get_age()を使用せず、直接m_ageを読むように以下のコードを追加。

    cout << "(backdoor)age of suzuki is " << suzuki.m_age << endl;

すると、コンパイル時に以下のように怒られる。

$ g++ main.cpp man.cpp
In file included from main.cpp:2:0:
man.h: In function ‘int main()’:
man.h:17:13: error: ‘int CMan::m_age’ is private
         int m_age;
             ^
main.cpp:13:53: error: within this context
     cout << "(backdoor)age of suzuki is " << suzuki.m_age << endl;
                                                     ^

privateメンバのm_ageにはアクセスできない。