简体   繁体   English

可以在方法而不是构造函数中初始化类的const成员变量吗?

[英]Can const member variable of class be initialized in a method instead of constructor?

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 int变量,但该类的构造函数中的变量值不可用。

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? 因为我只分配一次(如const所说)为什么它不起作用?

Code is as Following [Just a ProtoType] : 代码如下[Just a ProtoType]:

File : Ah 档案:啊

Class A
{
  private :
  const long int iConstValue;

  public :
  A();
  initClassA();
}

File : A.cpp 档案: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? 有人有任何解决方案吗?

NOTE : I Can not get value for iconstValue in constructor by any way as there are some restriction. 注意:无法以任何方式获取构造函数中iconstValue的值,因为存在一些限制。 So Please don't suggest to do that. 所以请不要建议这样做。

A small example: 一个小例子:

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

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

const doesn't mean you can only assign it once, you can never assign to a const object. const并不意味着你只能分配一次,你永远不能分配给const对象。 A const variable is initialized once and its value cannot change. const变量初始化一次,其值不能改变。 So you initialize it in the constructor, when all members and bases are initialized, then you can't change it after that. 所以你在构造函数中初始化它,当所有成员和基数都被初始化时,那么你就不能在那之后改变它。

If you can't get the value on construction you could either make the variable non-const, so you modify it, or maybe you could delay construction until you have all the data, using a placeholder until you construct the real object. 如果你无法获得构造的值,你可以使变量非常量,所以你修改它,或者你可以延迟构造,直到你拥有所有数据,使用占位符,直到你构造真实对象。

Two-stage construction is a code smell, it's certainly incompatible with const members. 两阶段构造是代码气味,它肯定与const成员不兼容。

You cannot do that, because you cannot change the value of a const variable. 你不能这样做,因为你不能改变const变量的值。 by the time initClassA runs the const data member has already been initialized (to some garbage value in this case). initClassA运行时,const数据成员已经被初始化(在这种情况下为一些垃圾值)。 So you can only really initialize the data member to some value in the constructor initializer list. 因此,您只能在构造函数初始化列表中将数据成员初始化为某个值。

If you want to set the variable only once, then you can make is non-const, and add a guard so it can only be set once. 如果你只想设置变量一次,那么你可以使非const,并添加一个后卫,这样它只能设置一次。 This isn't pretty but it would work: 这不是很漂亮,但它会起作用:

class A
{
  private :
   long int iValue;
   bool isInitialised;

  public :
  A() : iValue(0), isInitialized(false);
  bool initClassA() {
    if (isInitialized) return false;
    iValue = something:
    isInitialized = true;
    return true;
  }
}

But it isn't good practice to have objects that can be initialized or not. 但是,拥有可以初始化的对象并不是一个好习惯。 Objects should be in a coherent state when constructed, and clients should not have to check whether these objects are initialized. 构造时,对象应处于连贯状态,客户端不必检查这些对象是否已初始化。

Maybe what you can do, is change for a int pointer, receive this pointer in your constructor, and change the pointer where you want :P 也许您可以做的是,更改为int指针,在构造函数中接收此指针,并将指针更改为您想要的位置:P

But it will not be the same functionnality cause it will be the pointer which is const and not anymore the value :/ 但它不会是相同的功能,因为它将是const的指针,而不再是值:/

I think I need to change the design and I should calculate the (or get) the const variables value at constructor any how. 我想我需要改变设计,我应该在构造函数中计算(或得到)const变量值。 As there is no way I can set it's value later. 因为我无法在以后设定它的价值。

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

相关问题 我可以使用在 class 构造函数中初始化的流类型的成员变量吗? - Can I use a member variable of type ofstream initialized in the class constructor? 将类初始化的const成员传递给Base构造函数? - Pass in-class initialized const member to Base constructor? C ++类成员未初始化(在构造函数中,但在initialize方法中) - C++ class member not initialized (at constructor, but does at initialize method) C ++在头文件或构造函数中初始化const类成员变量? - C++ Initialize const class member variable in header file or in constructor? 继承的构造函数无法初始化抽象类的继承成员 - Inherited member from an abstract class can't be initialized by the inherited constructor 常量类成员副本构造函数 - Const Class Member Copy Constructor const_cast类构造函数中的const成员 - const_cast a const member in a class constructor 为什么我不能使类内初始化的`const const std::string` 成为静态成员 - Why can't I make in-class initialized `const const std::string` a static member 可以在C ++构造函数中初始化const成员吗? - Can const member be initialized in c++ construtor? C++:哪个先被调用/初始化? 其成员变量的类构造函数或构造函数? - C++: Which gets called/initialized first? The Class constructor or constructor(s) of its member variable(s)?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM