我有这个样品:
#include <iostream>
using namespace std;
class A {
public:
int x;
A(int one) { x = one; }
int getX() { return x; }
};
void main()
{
A first(5);
first = 10;
}
在这里,在main的两行中都调用构造函数。
但是如果我们在类中有多个变量,那么有没有可能用运算符=
调用构造函数呢?
就像在这里:
class A {
public:
int x,y;
A(int one,int sec) { x = one; y=sec;}
int getX() { return x; }
int getY() { return y; }
};
然后像这样使用=
创建一个类变量?
A example=(50,40)
是的,从C++11开始,您可以像下面这样通过复制列表初始化来实现:
A example = {50, 40};
example = {40, 50};