通过分配初始化类对象

时间:2019-07-06 12:57:19

标签: c++ class constructor initialization assignment-operator

我今天正在对构造函数进行一些实验:

class cls
{
    int a;
public:
    cls(){cout<<"Default constructor called\n";}
    cls(int b){a=b;cout<<"Constructor with parameter called";}
}

然后进行这种初始化

cls x=5;

产生一个输出,表明带有参数的构造函数已被调用。

我的问题i:如果我的构造函数带有两个或多个参数该怎么办?我还可以按分配使用初始化吗?

1 个答案:

答案 0 :(得分:1)

您可以使用更多类似的参数来做同样的事情:

#include <iostream>

class cls
{
    int a;
    double b;
public:
    cls(){std::cout<<"Default constructor called\n";}
    cls(int a): a(a){std::cout<<"Constructor with parameter called";}
    cls(int a, double b) : a(a), b(b){std::cout<<"Constructor with two parameter called";}
};

int main()
{
    cls t = {1, 1.5};
    return 0;
}