qfedu-cpp-level/day3/d3.cpp

45 lines
706 B
C++
Raw Permalink Normal View History

// 构造函数的分类与调用
#include <iostream>
using namespace std;
class B
{
private:
int n;
public:
// B() { cout << "B()" << endl; }
B(int n)
{
cout << "B(int n)" << endl;
this->n = n;
}
B(const B &other)
{
cout << "B(B &other)" << endl;
this->n = other.n;
}
public:
void showN()
{
cout << "n = " << n << endl;
}
};
int main()
{
B b1 = 20; // 隐式调用 B(int n), B(20), 只创建一个对象
B b2 = B(30); // 显式调用 B(int n)
B b3 = b2; // 隐式调用 B(B &other)
B &b4 = b3; // 不会创建空间,只是一个别名
B b5(b4); // 显式调用 B(B &other)
return 0;
}