Const 仍然允许在运算符函数 c++ 下进行更改

Const still allowing changes under operator function c++

本文关键字:c++ 函数 运算符 Const      更新时间:2023-10-16

我有以下代码:

StringC StringC::operator+(const StringC& other) const
{
    strcat(ps,other.ps);
    return ps;
};

相关标头如下:

class StringC {
private:
    char* ps;
public:
    StringC(char const *);
    StringC& operator=(const StringC&);
    StringC operator+(const StringC& other) const;
    void Print();

我的理解是,在operator+函数中使用const应该阻止我更改psother但是我仍然能够更改它们。

我尝试了以下方法:

void Class1::Method1() const
{
    Variable = Variable + 1;
};
void Class1::Method1(const int v)
{
    v = 0;
    Variable = v + 1;
};

正如预期的那样,这个错误,我假设我在使用 const 时遗漏了一些东西,但本来会期望第一个代码在使用时出错strcat

我的理解是,在operator+函数中使用const应该阻止我更改psother但是我仍然能够更改它们。

这是正确的。 你不能改变psother.ps,但是,这不是你正在做的事情。 你正在做的是改变ps指向的内容,这不是恒常量。

因此,在operator+中,ps的类型是char * const(指向 char 的常量指针(而不是const char *(指向常量 char 的指针(