简体   繁体   English

我可以在C ++类中将成员变量声明为const吗?

[英]Can i declare member variable as const in class of c++?if yes,how?

我可以在C ++类中将成员变量声明为const吗?

You can - you put const in front of the type name. 您可以-将const放在类型名称的前面。

class C
{
     const int x;

public:
      C() : x (5) { }
};

You declare it as you would if it wasn't a member. 如果它不是成员,则可以声明它。 Note that declaring a variable as const will have considerable effects on the way that the class is used. 注意,将变量声明为const将对使用类的方式产生很大影响。 You will definitely need a constructor to initialise it: 您肯定需要一个构造函数来初始化它:

class A {
    public:
        A( int x ) : cvar( x ) {}
    private:
        const int cvar;
};

Sure, the simplest way is like this if the value will be the same across all instances of your class: 当然,如果类的所有实例的值都相同,则最简单的方法是这样的:

class X
{
public:
    static const int i = 1;
};

Or if you don't want it static: 或者,如果您不希望它是静态的:

class X
{
public:
    const int i;
    X(int the_i) : i(the_i)
    {     
    }
};

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM