c++ how to write a constructor?

核能气质少年 提交于 2019-12-24 00:08:45

问题


I'm not used to c++ and I'm having a problem writing a constructor.
See this example, is a short version of the code I'm working on:

class B {
public:
  B(int x);
}

class A {
public:
  B b;
  A(){
    // here I have to initialize b
  }
}

That throws a compiler error since I need to initialize b in A's constructor because B does not have a default constructor.

I think I have do it in the initialization list, but the B(int x) argument is a value I have to calculate with some algorithm, so I don't know how this should be properly done, or if I'm missing something or doing it wrong.

In other language like java I would have a reference to B and initialize it inside the A's constructor after the other code I need to get the value for the initialization.

What would be the right way to initialize b in this case?

Thanks!


回答1:


You can invoke functions in your constructor initializer list

class B {
public:
  B(int x);
}; // note semicolon

class A {
public:
  B b;

  A()
  :b(calculateValue()) {
    // here I have to initialize b
  }

  static int calculateValue() {
    /* ... */
  }
}; // note semicolon

Note that in the initializer list, the class is considered completely defined, so you can see members declared later on too. Also better not use non-static functions in the constructor initializer list, since not all members have yet been initialized at that point. A static member function call is fine.




回答2:


You use an initializer list, something like this:

A() : b(f(x)) {}



回答3:


#include<iostream>

class B {
    public:
        B(){} // A default constructor is a must, if you have other variations of constructor
        B(int x){}
}; // class body ends with a semicolon

class A {
    private:
        B b;
    public:
        A(){
            // here I have to initialize b
        }
        void write(){
            std::cout<<"Awesome";
        }
};

int main(){
    A a;
    a.write();
}

In C++, if you have a constructor that takes an argument, a default constructor is a must, unlike other languages as Java. That's all you need to change. Thanks.



来源:https://stackoverflow.com/questions/5507545/c-how-to-write-a-constructor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!