您的位置:首页 > 其它

拷贝构造函数

2015-07-07 15:36 232 查看
下面是关于拷贝构造函数的使用。

#include <iostream>
#include <string.h>
class CVector{
std::string *ptr;
public:
//default constructor
CVector(){
ptr = new std::string;
}
//constructor with one parameter
CVector(std::string s){
ptr = new std::string(s);
}
//destructor
~CVector(){
delete ptr;
}
// copy constructor
CVector(const CVector& c) : ptr(new std::string(c.getContent())){} //因为这里产生了一个恒定对象而其恒定对象只能调用 恒定函数getContent
// get content
const std::string &getContent() const{ //所以需要将getContent变成恒定函数 否则会报错
return *ptr;
}
};
int main(){
CVector s("ysh");
CVector temp(s);
std::cout << temp.getContent() << std::endl;
return 0;
}

如果未将getContent设置为const函数,就会报一下错误

/ubuntu/workspace/Tom/static.cpp:19:70: error: passing ‘const CVector’ as ‘this’ argument of ‘const string& CVector::getContent()’ discards qualifiers [-fpermissive]                                                                                

         CVector(const CVector& c) : ptr(new std::string(c.getContent())){}         
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: