目录1.同一类中的对象1复制给对象22.以对象为函数的形参3.函数返回是类的对象例题如下(让我记忆犹新)1.同一类中的对象1复制给对象2 同样是Point p1; Point p2;
同样是Point p1; Point p2;
例如:
int main(){
Point p1(1,2);
Point p2=p1; //这两种都会调用复制构造函数
Point p3(p1);
return 0;
}
例如:
void fun(Point p){ //p 作为了形参
cout<<p.height<<endl;
}
void fun2(){
Point p1(1,3);
return p1;
}
//或者还有返回*this的形式
void fun3(){
Point p2(5,8);
x+=4;
y+=6;
return *this;
}
注意:如果意外使用return *this;
导致调用的复制构造函数里面会输出多余的语句(这些语句不可删除)
那么我们应该 让此函数的返回类型改为 void
设计一个自己的字符串类MyString,内部有一个私有成员char *sptr;该成员用于创建字符串对象时,在内部使用动态内存分配的方法分配一个字符数组用于存储字符串的内容。
main函数已经写好,请根据main函数的内容完成该类的设计:
int main(){
MyString s1;
MyString s2("Hello");
MyString s3(s2);
s1.printString();
s2.printString();
s3.printString();
cout<<s1.getSize()<<" "<<s2.getSize()<<" "<<s3.getSize()<<endl;
MyString s4("HiChina");
s2.strinGCopy(s4);
s2.printString();
s3.stringCat(s4);
s3.printString();
return 0;
}
正确解答如下:
//不包括主函数main部分
#include<bits/stdc++.h>
using namespace std;
class MyString{
char *sptr;
int size;
public:
MyString(){
size=0;
sptr=new char[1];
sptr[0]='\0';
cout<<"Object Constructed. No Memory Allocated."<<endl;
}
MyString(char* s){//s是指针
size=strlen(s);
sptr=new char[size+1];
sptr[size]='\0';
strcpy(sptr,s);
cout<<"Object Constructed. "<<size+1<<" Bytes Allocated."<<endl;
}
MyString(const MyString&s){//此处s是对象
size=s.size;
sptr=new char[size+1];
strcpy(sptr,s.sptr);
cout<<"Object Constructed. "<<size+1<<" Bytes Allocated."<<endl;
}
~MyString(){
if(sptr[0]=='\0'){cout<<"Object Destructed. No Memory Freed."<<endl;}
else{
cout<<"Object Destructed. "<<size+1<<" Bytes Freed."<<endl;
}
delete[]sptr;
}
void printString(){
if(!size){cout<<"No Memory Allocated In This Object."<<endl;}
else cout<<sptr<<endl;
}
int getSize(){
return size;
}
void stringCopy(MyString&s){
cout<<"String Copy, "<<s.size+1<<" Bytes Reallocated And "<<size+1<<" Bytes Freed."<<endl;
size=s.size;
sptr=new char[size+1];
strcpy(sptr,s.sptr);
sptr[s.size]='\0'; //没有return *this
}
void stringCat(MyString&p){
char *p1=new char [size+p.size+1];
size=size+p.size;
cout<<"String Connection, "<<size+1<<" Bytes Reallocated And "<<p.size-1<<" Bytes Freed."<<endl;
strcpy(p1,sptr);//p1是换杯子
sptr=new char [size+p.size+1];//创建新的大空间
strcpy(sptr,p1);
strcat(sptr,p.sptr);
}
};
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。
--结束END--
本文标题: C++中调用复制(拷贝)函数的三种情况总结
本文链接: https://www.lsjlt.com/news/170793.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0