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*’
private:
int num;
string* sp;
sp is non-const, but p is:
const string* p = 0
The result is that this sp(p) is basically this:
string* sp = (const string*)0;
It's complaining because doing this would remove the string's const-ness.
This is because your sp member is not const.
string* sp;
But your parameter p is a const. The result is that you are trying to assign a const pointer to a non-const pointer - hence the error.
To fix this, you need to declare sp const at as well.
const string* sp;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With