我正在编写一些 C++ 类,其中一个类将另一个类的实例作为属性。在编写类构造函数时,我不断收到错误消息“类 Foo 不存在默认构造函数”。这是一个重现错误的小示例:
class Foo {
int size;
char name;
Foo(int s,char n) {
size = s;
name = n;
}
};
class Bar {
int size;
char name;
Foo foo;
Bar(int s, char n,Foo f){
size = s;
name = n;
foo = f;
}
};
Run Code Online (Sandbox Code Playgroud)
如果我删除 Foo 的类构造函数以便使用默认构造函数,错误就会消失。由于我将 Foo 类的现有实例传递到 Bar 的构造函数中,我不明白为什么错误会谈论 Foo 的构造函数。为什么会出现错误?以及如何修复代码?
// You probably want these to be a struct, not class.
// This way all members are public by default.
struct Foo {
int size;
char name;
Foo(int s,char n) : size{s}, name{n} {}
};
struct Bar {
int size;
char name;
Foo foo;
Bar(int s, char n, const Foo &f) : size{s}, name{n}, foo{f} {}
};
Run Code Online (Sandbox Code Playgroud)
当您不在初始化列表中初始化成员变量时,这与默认构造它然后重新分配值相同。所以你无缘无故地做了两倍的工作。(另见构造函数和成员初始值设定项列表)
因为你已经为你的结构定义了一个构造函数,默认的构造函数被隐式删除,这会导致你的编译错误。
附带说明一下,您甚至可能不需要这些构造函数,而是可以使用聚合初始化,如下所示:
struct Foo {
int size;
char name;
};
void example() {
Foo foo = {1, 'a'}; // the = is optional
}
Run Code Online (Sandbox Code Playgroud)