在类中初始化的const

时间:2012-11-28 14:27:17

标签: c++ class const

是否可以在class中的global const class method进行初始化?我想在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中设置method

5 个答案:

答案 0 :(得分:4)

没有。您可以在构造函数初始化程序中初始化它,但一旦初始化,const成员就无法更改。否则,它不会是const蚂蚁,现在,不是吗?

答案 1 :(得分:3)

这只能在你的类的构造函数中使用,并且只能在initializer-list中使用:

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

答案 2 :(得分:2)

不,你只能在构造函数中设置它。建成之后,它就是一成不变的。

答案 3 :(得分:1)

如上所述,您需要使用initializer list

初始化对象的const成员
/* a.h */
class A {
private:
    const string cs;

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

对于班级的每个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)
        {};
};

如果您不想提供构造函数来初始化每个值,可以在默认构造函数中提供默认值,但请记住在构造之后无法更改值:

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')
        {};
};

构造函数初始化列表对初始化其他成员也很有用,比如引用o不提供默认构造函数的复杂数据:

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;
};

答案 4 :(得分:0)

由于所有其他答案都已断言,您无法在初始化后更改const类成员的值。但是,有些人认为他们非常聪明并使用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; }
};

使用gnu和intel编译器,这实际上编译时没有警告AFAIK,甚至可能工作。但这违反了语言规则,构成了可怕的UB(未定义的行为)。换句话说,它可能并不总是按预期工作,因为允许编译器假定x自初始化以来没有改变。

相关问题