下面是关于拷贝构造函数的使用。
#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())){}