C++言語ベースインスタンスオブジェクトメンバーの参照
3946 ワード
賀先生の授業リンクこの授業の説明
オブジェクト名とメンバー演算子によるオブジェクト内のメンバーへのアクセス
オブジェクトへのポインタによるオブジェクト内のメンバーへのアクセス
オブジェクトの参照変数からオブジェクトのメンバーにアクセス
プライベート・データ・メンバーへのアクセスの一般的な方法
(1)パブリック関数によるプライベートメンバーへのアクセス
(2)(慣例)setとget関数を用いてプライベートデータメンバーにアクセスする
ポインタを使用してプライベート・データ・メンバーの値をクラス外に抽出
参照を使用してプライベート・データ・メンバーの値をクラス外に抽出
オブジェクト名とメンバー演算子によるオブジェクト内のメンバーへのアクセス
#include <iostream>
using namespace std;
class Time
{
public:
void set_time( );
void show_time( );
private:
int hour;
int minute;
int sec;
};
int main( )
{
Time t1;
t1.set_time( );
t1.show_time( );
Time t2;
t2.set_time( );
t2.show_time( );
return 0;
}
void Time::set_time( )
{
cin>>hour;
cin>>minute;
cin>>sec;
}
void Time::show_time( )
{
cout<<hour<<":"<<minute<<":"<<sec<<endl;
}
オブジェクトへのポインタによるオブジェクト内のメンバーへのアクセス
#include <iostream>
using namespace std;
class Time
{
public:
void set_time( );
void show_time( );
private:
int hour;
int minute;
int sec;
};
int main( )
{
Time t1, *p;
p=&t1;
t1.set_time( );
(*p).show_time( );
p->show_time( );
return 0;
}
void Time::set_time( )
{
cin>>hour;
cin>>minute;
cin>>sec;
}
void Time::show_time( )
{
cout<<hour<<":"<<minute<<":"<<sec<<endl;
}
オブジェクトの参照変数からオブジェクトのメンバーにアクセス
#include <iostream>
using namespace std;
class Time
{
public:
void set_time( );
void show_time( );
private:
int hour;
int minute;
int sec;
};
int main( )
{
Time t1;
Time &t2=t1;
t1.set_time( );
t2.show_time( );
return 0;
}
void Time::set_time( )
{
cin>>hour;
cin>>minute;
cin>>sec;
}
void Time::show_time( )
{
cout<<hour<<":"<<minute<<":"<<sec<<endl;
}
プライベート・データ・メンバーへのアクセスの一般的な方法
(1)パブリック関数によるプライベートメンバーへのアクセス
#include <iostream>
using namespace std;
class Test
{
private:
int x, y;
public:
void setX(int a)
{
x=a;
}
void setY(int b)
{
y=b;
}
void printXY(void)
{
cout<<"x="<<x<<'\t'<<"y="<<y<<endl;
}
} ;
int main()
{
Test p1;
p1.setX(3);
p1.setY(5);
p1.printXY( );
return 0;
}
(2)(慣例)setとget関数を用いてプライベートデータメンバーにアクセスする
#include <iostream>
using namespace std;
class Test
{
private:
int x,y;
public:
void setX(int a) {x=a;}
void setY(int b) {y=b;}
int getX(void) {return x;} // x
int getY(void) {return y;} // y
};
int main()
{
Test p1,p2;
p1.setX(3);p1.setY(5);
int a,b;
a=p1.getX( ); b=p1.getY();
cout<<a<<'\t'<<b<<endl;
}
ポインタを使用してプライベート・データ・メンバーの値をクラス外に抽出
#include <iostream>
using namespace std;
class Test
{
private:
int x,y;
public:
void setX(int a)
{
x=a;
}
void setY(int b)
{
y=b;
}
void getXY(int *px, int *py)
{
*px=x; // x,y
*py=y;
}
};
int main()
{
Test p1;
p1.setX(3);
p1.setY(5);
int a,b;
p1.getXY(&a,&b); // a=x, b=y
cout<<a<<'\t'<<b<<endl;
return 0;
}
参照を使用してプライベート・データ・メンバーの値をクラス外に抽出
#include <iostream>
using namespace std;
class Test
{
private:
int x,y;
public:
void setX(int a)
{
x=a;
}
void setY(int b)
{
y=b;
}
void getXY(int &px, int &py) //
{
px=x; // x,y
py=y;
}
};
int main()
{
Test p1;
p1.setX(3);
p1.setY(5);
int a,b;
p1.getXY(a, b); // a=x, b=y
cout<<a<<'\t'<<b<<endl;
return 0;
}