C ++相当于Python的__init__

时间:2017-08-23 02:00:48

标签: python c++

在学习使用C ++编写代码时,在很多情况下,当我声明类给出变量值时,我需要运行代码。我在Python中知道你可以使用__init__,但我怎么能在C ++中这样做呢?

2 个答案:

答案 0 :(得分:4)

C ++中Python的__init__方法的等效方法称为constructor。两者的作用是初始化/构造类的实例以便可用。但是有一些不同之处。

  • 在Python中,数据成员在__init__内初始化,而在C ++中,应使用初始化列表初始化它们。

  • 在C ++中,构造函数默认链接到父类的默认构造函数,而在Python中,您必须显式调用父__init__,最好通过super()

  • C ++允许函数重载,它扩展到构造函数。这允许声明具有不同签名(参数列表)的不同构造函数。要在Python中执行相同的操作,您必须将__init__声明为接受*args,**kwargs并根据这些内容手动分发。

  • 在C ++中,有一些空间构造函数,即default constructorcopy constructormove constructor

实施例

的Python:

class Foo:
    def __init__(self, x):
        self.x = x
        print "Foo ready"

C ++:

class Foo {
public:
    int x;
    Foo(int x) : x(x)
    {
        std::cout << "Foo ready\n";
    }
};

答案 1 :(得分:-1)

它被称为默认构造函数:

class X {
public:
  // only one of the next two lines should be present as the are both default constructors and having both would make it ambiguous which to use
  X();                       // Default constructor with no arguments
  X(int = 0);                // Default constructor with one default argument

  X(int, int , int = 0);     // Non-Default Constructor
};
相关问题