【发布时间】:2021-09-19 13:35:05
【问题描述】:
class Vect {
public:
Vect(int n);
~Vect();
Vect(const Vect& original);
private:
int* data;
int size;
};
Vect::Vect(int n) {
size = n;
data = new int[n];
}
Vect::~Vect() {
delete [] data;
}
Vect::Vect(const Vect& original) {
size = original.size;
data = new int[size];
for (int i = 0; i < size; ++i) {
data[i] = original.data[i];
}
}
#include <bits/stdc++.h>
using namespace std;
int main(void) {
Vect a(100);
Vect b = a;
Vect c;
c = a;
return 0;
}
我现在有一个 Vect 类,在 main 中我创建了一个变量 c 保存的 Vect 对象,c.size 的默认大小是多少? 或者它不会有任何默认值? 如果它没有默认值,那么 b 怎么会有 100(因为 a.size 现在等于 b.size)?
【问题讨论】:
-
由于没有默认构造函数,
Vect的实例无法为其任何数据成员设置某种默认值。由于没有匹配的函数调用,代码将无法编译。 -
您的意思是“int 变量的默认值”吗?
-
非类成员(如
int和int *)没有默认值。如果它们未初始化,则它们具有不确定的值,并且使用这些值会导致未定义的行为。 -
即使添加了默认构造函数,这段代码仍然不符合三规则,因为
c = a;是复制分配,不是用户定义的,因此是默认提供的(即成员副本,最终会导致分配后潜在的内存泄漏和销毁时的双重删除)。 -
关于不相关的问题,请阅读Why should I not #include <bits/stdc++.h>? 和Why is “using namespace std;” considered bad practice? 在更相关的说明中,请获取some good books 阅读并了解有关构造函数和“默认值”的所有详细信息想知道。