类的const成员变量可以在方法中初始化而不是构造函数? [英] Can const member variable of class be initialized in a method instead of constructor?

查看:278
本文介绍了类的const成员变量可以在方法中初始化而不是构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类,并且想要创建一个const int变量,但该变量的值在类的构造函数中不可用。

I have a class and want to create a const int variable but the value for the variable is not available to me in constructor of the class.

在初始化方法的类我得到的价值。我可以在该方法中分配吗?
因为我只赋值一次(const说)为什么它不工作?

In initialization method of the class i get the value. Can I assign it in that method? As I am assigning it only once (as const says) why it isn't working?

代码如下[Just ProtoType]:

Code is as Following [Just a ProtoType] :

File:Ah

Class A
{
  private :
  const long int iConstValue;

  public :
  A();
  initClassA();
}

文件:A.cpp

File : A.cpp

A::A()
{
 //CanNot initialize iConstValue (Don't have it)
}

A::initClassA(some params)
{
 // calculation according to params for iConstValue
 iConstValue = (some value)
}

这不工作。有人有任何解决方案?

This is not working. Somebody has any Solutions?

注意:我无法通过任何方式获得iconstValue在构造函数中的值是一些限制。

推荐答案

一个小例子:

class A
{
public:
  A():a(initial_value_of_a()) {}

private:
  const int a;
  int initial_value_of_a() { return 5; /* some computation here */ };
};

这篇关于类的const成员变量可以在方法中初始化而不是构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆