为什么我不能使用“const string* sp = 0”在构造函数中初始化
我的问题是 const string* p
给了我一个错误。这有什么问题吗?因为我不会改变原来的值。 const int& n = 0 工作正常。
#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;
}
输出错误是:
error: invalid conversion from ‘const std::string*’ to ‘std::string*’
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*’
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
sp
是非常量,但p
是:结果是这个
sp(p)
基本上是这样的:它在抱怨,因为这样做会删除字符串的
const
性质。sp
is non-const, butp
is:The result is that this
sp(p)
is basically this:It's complaining because doing this would remove the string's
const
-ness.这是因为您的
sp
成员不是const
。但是你的参数
p
是一个const
。结果是您试图将 const 指针分配给非常量指针 - 因此会出现错误。要解决此问题,您还需要声明
sp
const at 。This is because your
sp
member is notconst
.But your parameter
p
is aconst
. The result is that you are trying to assign aconst
pointer to a non-const pointer - hence the error.To fix this, you need to declare
sp
const at as well.我认为您对 const 的各种含义感到困惑。
声明一个指向常量对象的指针,该指针只允许访问类 string 的常量方法。
将指向字符串的指针声明为类的常量成员,您必须在构造函数中初始化 sp 并且不能更改(使用 const_cast<> 除外)。
在参数列表中意味着该函数承诺不会更改 num 引用的整数的值,但它当然可以复制其值(就像您所做的那样)。字符串指针的相应操作本来就是
完全合法的,尽管相当非正统。
I think you got confused by the various meanings of const.
declares a pointer to a constant object, which only allows access to constant methods of class string.
declares a pointer to a string to be a constant member of the class, which you must initialise sp in the constructor and cannot change (except using const_cast<>).
in the argument list means that the function promises not to alter the value of the integer referred to by num, but it can of course copy its value (as you did). The corresponding operation for the string pointer would have been
and would have been perfectly legal albeit rather unorthodox.