我最近在一次考试中遇到了以下代码:
#include <iostream>
using namespace std;
class A
{
int x;
public:
A(int i):x(i) {}
int get_x() const
{
return x;
}
};
class B : public A
{
int *y;
public:
B(int i) :A(i)
{
y = new int[i];
for (int j = 0; j < i; j++)
y[j] = 1;
}
B(B&);
int &operator[](int i)
{
return y[i];
}
};
B::B(B& b)///no matching function for call to A::A()
{
y = new int[b.get_x()];
for (int i = 0; i < b.get_x(); i++)
y[i] = b[i];
}
ostream &operator<<(ostream& o, B a)
{
for (int i = 0; i < a.get_x(); i++)
o << a[i];
return o;
}
int main()
{
B b(5);
cout << b;
return 0;
}
在我看来,将b
传递给operator<<
时,编译器需要对其进行复制,因此将其传递给B的复制构造函数。但是为什么复制构造函数需要{ {1}}?它不应该只使用A中的默认副本构造函数并执行A::A()
的浅表副本吗?