拷贝构造函数
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())){}
#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())){}
相关文章推荐
- php抽象类用法实例分析
- SQL语句将某字段查询出以逗号隔开
- PayPal高级工程总监:读完这100篇论文 就能成大数据高手
- shell脚本自学成才之helloWold
- sequence-ID in Dynamic Lookup
- chapter16test8
- position
- android加载本地和网上照片
- 【Java】编写一个方法,实现基本的字符串压缩功能
- Thrift可扩展高性能的通信服务框架
- java线程同步锁synchronized的认识
- migrate android code
- json的一些问题
- Spring2.5学习4.1_静态代理实现
- watch:定期重复Linux / Unix命令
- Spring2.5学习4.1_静态代理实现
- css学习笔记
- VS2012中进行Web性能和负载测试
- ios 设置启动图时间
- C#语言基础之数据类型