gpt4 book ai didi

c++ - 为什么初始化对象的两种不同方式给出不同的输出

转载 作者:行者123 更新时间:2023-11-30 00:43:46 25 4
gpt4 key购买 nike

考虑以下代码

#include <iostream> 
using namespace std;

class A
{
int x;
public:
A() { cout << "A's constructor called " << endl; }
};

class B
{
public:
static A a;

B() { cout << "B's constructor called " << endl; }
static A getA() { return a; }
};

A B::a; // definition of a

int main()
{
B b1, b2, b3;
A a = b1.getA();

cout<<&a<<endl;

cout<<&B::a;

return 0;
}

输出是

A's constructor called 
B's constructor called
B's constructor called
B's constructor called
0x7fff03081280
0x601194

现在让我们考虑另一个类似的代码

    #include <iostream> 
using namespace std;

class A
{
int x;
public:
A() { cout << "A's constructor called " << endl; }
};

class B
{
public:
static A a;

B() { cout << "B's constructor called " << endl; }
static A getA() { return a; }
};

A B::a; // definition of a

int main()
{
B b1, b2, b3;
A a ;
a= b1.getA();

cout<<&a<<endl;
cout<<&B::a;

return 0;
}

输出是

A's constructor called 
B's constructor called
B's constructor called
B's constructor called
A's constructor called
0x7ffc485a1070
0x601194

现在我的问题是,为什么在第一种情况下 A 的构造函数只被调用一次,而在第二种情况下它被调用两次。

另外两个输出 &a 和 &B::a 是不同的,所以这意味着它们是两个不同的对象。

请解释为什么会这样。

最佳答案

在你的第一个代码中

A a = b1.getA(); 

A 的复制构造函数被调用,它不会生成任何输出。自己定义它,您将获得与第二个代码类似的输出。

关于c++ - 为什么初始化对象的两种不同方式给出不同的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52492894/

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