my problem is that const string* p gives me an error. What is wrong with this? since I am not change the original value. const int& n = 0 works fine.
#include <iostream>
using namespace std;
class HasPtr
{
private:
int num;
string* sp;
public:
//constructor
HasPtr(const int& n = 0, const string* p = 0): num(n), sp(p) {}
//copy-constructor
HasPtr(const HasPtr& m): num(m.num), sp(m.sp) {}
//assignment operator
HasPtr& operator=(const HasPtr& m)
{
num = m.num;
sp = m.sp;
return *this;
}
//destructor
~HasPtr() {}
};
int main ()
{
return 0;
}
output Error is :
error: invalid conversion from ‘const std::string*’ to ‘std::string*’
This is because your
spmember is notconst.But your parameter
pis aconst. The result is that you are trying to assign aconstpointer to a non-const pointer – hence the error.To fix this, you need to declare
spconst at as well.