gpt4 book ai didi

c++ - 括号与花括号

转载 作者:太空宇宙 更新时间:2023-11-04 14:53:00 26 4
gpt4 key购买 nike

#include<iostream>
using namespace std;
class test
{
public:
int a,b;

test()
{
cout<<"default construictor";

}
test(int x,int y):a(x),b(y){

cout<<"parmetrized constructor";
}

};
int main()
{

test t;
cout<<t.a;
//t=(2,3);->gives error
t={2,3}; //calls paramterized constructor
cout<<t.a;
}

输出:- 默认构造函数 4196576 参数化构造函数 2

为什么在上面的例子中,参数化构造函数(即使默认构造函数已经被调用。)在 {} 而不是 () 的情况下被调用

最佳答案

我添加了一些额外的代码来展示实际发生的事情。

#include<iostream>
using namespace std;

class test
{
public:
int a,b;

test()
{
cout << "default constructor" << endl;
}

~test()
{
cout << "destructor" << endl;
}

test(int x,int y):a(x),b(y)
{
cout << "parameterized constructor" << endl;
}

test& operator=(const test& rhs)
{
a = rhs.a;
b = rhs.b;
cout << "assignment operator" << endl;
return *this;
}

};

int main()
{

test t;
cout << t.a << endl;
//t=(2,3);->gives error
t={2,3}; //calls parameterized constructor
cout << t.a << endl;
}

输出:

default constructor
4197760
parameterized constructor
assignment operator
destructor
2
destructor

所以语句t={2,3};实际上是使用参数化构造函数构造一个新的test对象,调用赋值运算符设置t 等于新的临时 test 对象,然后销毁临时 test 对象。它等同于语句 t=test(2,3)

关于c++ - 括号与花括号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42479580/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com