c++ - 在类中初始化 const

标签 c++ class constants

是否可以在中用类方法初始化一个global const?我想在我的 class 中使用一个方法来设置 const

我的想法是:

/* a.h */
class A {
private:
    const string cs;

public:
    A();
    ~A();

    bool cs(const string &host, ...)
};

/* a.cpp */
A::A(){
}

A::~A(){
}

bool cs(const string &host, ...) {
    /* check some values */
    cs = "Set Vaule";   //Doesnt work, get an compiler error
}

是否可以在方法中设置一个global const

最佳答案

没有。您可以在构造函数初始化器中对其进行初始化,但一旦初始化,const 成员就无法更改。否则,它就不会是 constant 了,不是吗?

关于c++ - 在类中初始化 const,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13607370/

相关文章:

typescript - 使用 typescript 在构造函数中动态设置类属性

c++ - 具有常量变量的类的多个实例对常量使用相同的内存?

java - 字符数组与字符串 : which is better for storing a set of letters

c++ - 如何更改makefile中g++的版本

java - C++ 和 Java 之间的低延迟 IPC

php - 如何在 PHP 中将类常量用于类属性?

c++ - const 变量的复杂初始化,同时避免新分配

c++ - 如何设置动态分配数组的内容?

c++ - execl() 返回 `cannot open or parse argument` 错误

c++ - 当一个对象被传递给它时,成员函数的行为会改变吗?