Copy Controlレプリケーション制御(レプリケーションコンストラクタcopy constructor,解析関数destructor,賦値オペレータoperator=
2766 ワード
#include <iostream>
using namespace std;
class Point{
public:
Point(int cx,int cy):x(cx),y(cy){
pData=new int;
*pData = 0;
}
Point(const Point& pt) //copy constructor
{
x=pt.getX();
this->y=pt.getY();
pData=new int;
*pData=pt.getData();
}
void to_str(){
cout<<"x="<<x<<",y="<<y<<",*pData="<<*pData<<endl;
}
void setX(int x){
this->x=x;
}
void setY(int y)
{
this->y=y;
}
void setData(int data)
{
*pData=data;
}
int getX() const
{
return x;
}
int getY() const
{
return y;
}
int getData() const
{
return *pData;
}
virtual ~ Point()
{
delete pData;
}
private:
int x,y,*pData;
};
int main()
{
Point pt(1,2);
pt.setData(123);
pt.to_str();
cout<<"Hello "<<endl;
Point pt2(pt);
pt2.setX(11);
pt2.setY(22);
pt2.setData(112233);
pt.to_str();
pt2.to_str();
return 0;
}
データメンバーがget、setメソッドを設定するかどうかについては、Google Cpp Style Guideを参照してください.
Access Control
link ▽
Make data members
private
, and provide access to them through accessor functions as needed (for technical reasons, we allow data members of a test fixture class to be protected
when using Google Test ). Typically a variable would be called
foo_
and the accessor function foo()
. You may also want a mutator function set_foo()
. Exception: static const
data members (typically called kFoo
) need not be private
. The definitions of accessors are usually inlined in the header file.
See also Inheritance and Function Names .
http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml?showone=Access_Control#Access_Control