C++对象拾遗
#include <iostream.h>
#include <string.h>
//using namespace std;
class A
{
public:
A();//默认构造函数
A(char *sName);//构造函数,一个参数
A(const A &Aobj);//拷贝构造函数
virtual ~A();//析构函数,一般可以声明为虚函数
void sayhello();
char m_sName[10];
private:
void saywellcome();
char m_sPassword[10];
};
int main()
{
A *obj=new A("loster");//构造函数,返回一个对象的指针
obj->sayhello();
cout<<obj->m_sName<<" public var"<<endl;//可以访问公共变量
//A *anthorobj=new A(*obj);//拷贝构造函数,拷贝的空间是独立的
A anthorobj(*obj);//此方式声明不需要delete,作用域为大括号,返回一个对象
strcpy(anthorobj.m_sName,"lamase");
anthorobj.sayhello();
delete obj;//此会调用析构函数,new必须delete
return 0;
}
void A::sayhello()
{
saywellcome();
cout<<"good afternoon "<<m_sName<<endl;
}
void A::saywellcome()
{
cout<<"wellcome"<<endl;
}
A::A()
{
strcpy(m_sName,"aliay");
strcpy(m_sPassword,"123456");
}
A::A(char *sName)
{
strcpy(m_sName,sName);
strcpy(m_sPassword,"000000");
}
A::A(const A &Aobjs)
{
strcpy(m_sName,Aobjs.m_sName);
strcpy(m_sPassword,Aobjs.m_sPassword);//这里是可以访问private的,因为可以算是类内访问
}
A::~A()
{
cout<<"delete obj"<<endl;
}
/******输出****************
wellcome
good afternoon loster
loster public var
wellcome
good afternoon lamase
delete obj
delete obj(注意这里自动调用了析构函数)
*****************************/