c++ - 写入 const API 函数中的成员变量 (C++)

标签 c++ qt overriding

我正在 QT GUI 项目中编写自定义 QValidator,我的理解是我需要扩展 QValidator 类,因为:

void setValidator(const QValidator *);

需要传递一个QValidator子类。 问题在于该函数:

virtual QValidator::State validate(QString& input, int& pos) const Q_DECL_OVERRIDE;

是const,但我需要在子类中写入验证状态,并且由于这个const属性,我无法写入任何成员变量。我怎样才能绕过这个 API 限制呢?

我正在做这样的事情:

QValidator::State IPv4Validator::validate(QString &input, int &pos) const
{
    auto validationResult = QRegExpValidator::validate(input, pos);
    // custom logic here:
    myMemberVariable = something(validationResult);
    // more logic 
    // more logic 
    // more logic 

    return validationResult;
}

提前致谢!

最佳答案

可以在 const 中写入成员变量通过声明成员变量 mutable 来实现函数或使用const_cast (不安全)。

struct A {
    void foo() const {
        a = 3;
        const_cast<A*>(this)->b = 4;
    }

    mutable int a;
    int b;
};

关于c++ - 写入 const API 函数中的成员变量 (C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42249675/

相关文章:

c# - 如何覆盖 [] 数组中的 ToString()?

c++ - 如何打开名称带有 unicode 符号的文件

c++ - Bullet Physics,btBvhTriangleMeshShape 和 btStaticPlaneShape 之间的碰撞不起作用

linux - 如何使用应用程序部署 Qt 库?

c++ - 在 DateEdit Qt C++ 中打开 .txt 中的日期

Python:HTMLParser 如何处理来自子标签的数据

c++ - vector 中字符串指针的覆盖输出运算符

c++ - shared_ptr 中对 const int 的 undefined reference

c++ - 使用空的 boost::accumulators

c++ - 在 QTreeWidget 中插入时自动排序