简体   繁体   English

在类中初始化const

[英]Initialized const in a class

Is it possible to initialize in a class a global const in a class method ? 是否可以在class中使用class method初始化global const I would like to use a method in my class to set the const . 我想用一个方法在我class设置const

My idea was: 我的想法是:

/* 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
}

Is It possible to set a global const in a method ? 是否可以在method设置global const

No. You could initialize it in a constructor initializer, but once initialized a const member cannot be changed. 不可以。您可以在构造函数初始值设定项中对其进行初始化,但是一旦初始化,便无法更改const成员。 Otherwise, it wouldn't be a const ant, now, would it? 否则,现在不是const ,不是吗?

This is only possible in the constructor of your class, and there only in the initializer-list: 这仅在您的类的构造函数中可行,并且仅在initializer-list中存在:

A() : cs("Set Value") {
}

No, you can only set it in a constructor. 不,您只能在构造函数中进行设置。 After construction, it's set in stone. 施工完成后,将其固定在石头上。

As mentioned, you need to initialize the const members of an object using its initializer list : 如前所述,您需要使用其初始化列表初始化一个对象的const成员:

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

public:
    A(const string &value) :
        cs(value) // <---- initialize here!.
    {};
};

It is the same for every const member of the class: 对于该类的每个const成员都是相同的:

class A {
private:
    const string cs;
    const float numberofthebeast;
    const char z;

public:
    A(const string &value, const float number, const char character) :
        cs(value),
        numberofthebeast(number),
        z(character)
        {};
};

If you don't want to provide a constructor to initialize each value, you can provide a default value in the default constructor, but remember that you cannot change the value after the construction: 如果您不想提供一个构造函数来初始化每个值,则可以在默认构造函数中提供一个默认值,但是请记住,构造后您不能更改该值:

class A {
private:
    const string cs;
    const float numberofthebeast;
    const char z;

public:
    A(const string &value, const float number, const char character) :
        cs(value),
        numberofthebeast(number),
        z(character)
        {};

    // Default values!!!
    A() :
        cs("default ctor"),
        numberofthebeast(666.666f),
        z('Z')
        {};
};

The constructor initializer list is also useful to initialize other members, like references o complex data that doesn't provide default constructor: 构造函数初始值设定项列表还可用于初始化其他成员,例如不提供默认构造函数的复杂数据的引用:

const unsigned float PI = 3.14f;

class Weird
{
    Weird (int w);
    // no default ctor!
    int W;
};

class Foo
{
    // Error: weird doesn't provide default ctor, 
    Weird w;
    // Error: reference uninitialized.
    float &pi;
};

class Bar
{
    Bar() :
        // Ok, Weird is constructed correctly.
        w(1),
        // Ok, pi is initialized.
        pi(PI)
    {};
    Weird w;
    float &pi;
};

As all the other answers have asserted, you cannot change the value of a const class member after initialization. 正如所有其他答案所断言的那样,您无法在初始化后更改const类成员的值。 However, some people think they are very clever and use the const_cast<> 但是,有些人认为他们非常聪明,并使用const_cast<>

class A {
  const int x;
public:
  A(int _x) : x(_x) {}
  void change_x(int _x)        // change x ?!
  { const_cast<int&>(x) = _x; }
};

With the gnu and intel compilers, this actually compiles without warning AFAIK and may even work. 使用gnu和intel编译器,它实际上在编译时不会警告AFAIK,甚至可能起作用。 But this violates the language rules and constitutes the dreaded UB (undefined behaviour). 但这违反了语言规则,并构成了令人恐惧的UB(未定义的行为)。 In other words, it may not always work as intended, since the compiler is allowed to assume that x is unchanged since initialization. 换句话说,它可能并不总是按预期工作,因为允许编译器假定自初始化以来x不变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么const类可以自己初始化? - Why can a const Class& be initialized to itself? 可以在方法而不是构造函数中初始化类的const成员变量吗? - Can const member variable of class be initialized in a method instead of constructor? 使用非常量值初始化的引用到续类成员 - reference-to-cont class member initialized with non-const value 内联初始化 static const class 成员的初始化顺序保证 - Initialization order guarantees for inline-initialized static const class member 只能在类中初始化静态const整数数据成员 - Only static const integral data members can be initialized within a class 将类初始化的const成员传递给Base构造函数? - Pass in-class initialized const member to Base constructor? 为什么我们必须定义一个在类中初始化的const静态成员 - Why we have to define a const static member that is initialized within a class 为什么我不能使类内初始化的`const const std::string` 成为静态成员 - Why can't I make in-class initialized `const const std::string` a static member const变量何时初始化 - When is const variable initialized 为什么在实际使用 class 之前,不需要在模板 class 中初始化 const 变量? - Why do const variables don't need to be initialized in a template class until the class is actually used?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM