qfedu-cpp-level/day3/d2.cpp

36 lines
586 B
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 构造函数的分类与调用
// 拷贝构造函数
#include <iostream>
using namespace std;
class A
{
public:
int x;
public:
A() {}
A(A &other) // 拷贝构造函数
{
this->x = other.x;
}
};
int main()
{
A a1; // 调用无参的构造函数进行初始化 a1 对象
a1.x = 10;
cout << "a1 x = " << a1.x << endl;
A a2(a1); // 使用拷贝构造
cout << "a2 x = " << a2.x << endl;
A *a3 = new A(); // 使用指针和new在堆空间创建对象
// a3->x = 20;
cout << "a3 x = " << a3->x << endl;
return 0;
}