WEB开发网
开发学院软件开发C++ C++对象作为函数参数 阅读

C++对象作为函数参数

 2012-05-25 09:19:48 来源:WEB开发网   
核心提示:对象作为函数参数l 对象本身做参数(传值),传对象副本l 对象引用做参数(传地址),C++对象作为函数参数,传对象本身l 对象指针做参数(传地址),传对象本身源代码://科目:C++实验4-2//题目:对象的调用//作者:武叶//语言:C++//创作时间:2012年4月16日#include < iostream

对象作为函数参数

l 对象本身做参数(传值),传对象副本

l 对象引用做参数(传地址),传对象本身

l 对象指针做参数(传地址),传对象本身


源代码:
//科目:C++实验4-2
//题目:对象的调用
//作者:武叶
//语言:C++
//创作时间:2012年4月16日
#include < iostream.h>
#include <string.h>
#include < stdlib.h>
class CStrSub
{
char *str;
public:
CStrSub(char *s);
CStrSub(CStrSub &);
~ CStrSub();
void set(char *s);
void show()
{
cout<<str<<endl;
}
};
CStrSub:: CStrSub(char *s)
{
str=new char[strlen(s)+1];
if(!str)
{
cout<<"申请空间失败!"<<endl;
exit(-1);
}
strcpy(str,s);
}
CStrSub:: CStrSub(CStrSub & temp)
{
str=new char[strlen(temp.str)+1];
if(!str)
{
cout<<"申请空间失败!"<<endl;
exit(-1);
}
strcpy(str,temp.str);
}
CStrSub:: ~ CStrSub( )
{
if(str!=NULL) delete [ ]str;
}
void CStrSub::set(char *s)
{
delete [ ]str;
str=new char[strlen(s)+1];
if(!str)
{
cout<<"申请空间失败!"<<endl;
exit(-1);
}
strcpy(str,s);
}
CStrSub input(CStrSub *temp)
{
char s[20];
cout<<"输入字符串:"<<endl;
cin>>s;
temp->set(s);
return *temp;
}
void main()
{
CStrSub a("hello");
a.show( );
CStrSub b=input(&a);
a.show( );
b.show( );

Tags:对象 作为 函数

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接