我有以下代码:
StringC StringC::operator+(const StringC& other) const
{
strcat(ps,other.ps);
return ps;
};
Run Code Online (Sandbox Code Playgroud)
相关标题如下:
class StringC {
private:
char* ps;
public:
StringC(char const *);
StringC& operator=(const StringC&);
StringC operator+(const StringC& other) const;
void Print();
Run Code Online (Sandbox Code Playgroud)
我的理解是,const在operator+函数中的使用应该阻止我能够改变ps,other但是我仍然能够改变它们.
我尝试过以下方法:
void Class1::Method1() const
{
Variable = Variable + 1;
};
void Class1::Method1(const int v)
{
v = 0;
Variable = v + 1;
};
Run Code Online (Sandbox Code Playgroud)
并且这个错误如预期的那样,我假设我在使用const时遗漏了一些东西,但是在使用时会产生错误的第一个代码strcat?
我的理解是,
const在operator+函数中的使用应该阻止我能够改变ps,other但是我仍然能够改变它们.
这是正确的.你无法改变,ps或者other.ps,这不是你正在做的事情.你正在做的是改变ps指向的内容,这不是const.
所以,在is operator+的类型(指向char的常量指针)而不是(指向常量char的指针)pschar * constconst char *