我无法编译此代码。看来问题出在Friends类的构造函数上,但是我不明白问题出在哪里。
我试图将其删除并成功编译,但是默认构造函数似乎无法正常运行。
这是编译器显示的内容:
UnNamed.cpp: In constructor ‘Friends::Friends()’:
UnNamed.cpp:92:13: error: no matching function for call to ‘Friend::Friend()’
Friends() {
^
UnNamed.cpp:52:3: note: candidate: Friend::Friend(std::__cxx11::string, std::__cxx11::string)
Friend (string n, string c): Person (n, c) {
^~~~~~
UnNamed.cpp:52:3: note: candidate expects 2 arguments, 0 provided
UnNamed.cpp:41:7: note: candidate: Friend::Friend(const Friend&)
class Friend: public Person {
^~~~~~
UnNamed.cpp:41:7: note: candidate expects 1 argument, 0 provided
UnNamed.cpp:41:7: note: candidate: Friend::Friend(Friend&&)
UnNamed.cpp:41:7: note: candidate expects 1 argument, 0 provided
代码如下:
#include <iostream>
#include <string>
using namespace std;
struct Date{
int d;
int m;
int y;
};
class Person{
protected:
string name;
string surname;
public:
Person(){
name = "xxx";
surname = "xxx";
}
Person (string n, string c) {
name = n;
surname = c;
}
string get_surname() {
return surname;
}
void print (ostream& f_out) const {
f_out << name << " " << surname;
}
};
class Friend: public Person {
private:
Date bdate;
string email;
bool bissextile( int a ) {...}
bool check_date() {...}
public:
Friend (string n, string c): Person (n, c) {
email = "xxx";
bdate.d = 1;
bdate.m = 1;
bdate.y = 1;
}
void set_date (int d, int m, int y) {...}
void set_email (string e) {
email = e;
}
void print ( ostream& f_out) {
f_out << name << " " << surname << " " << bdate.g << "/" << bdate.m <<"/" << " " << bdate.a << "/" << " " << email;
}
};
class Friends {
private:
Friend friend_list[100];
int i;
public:
Friends() {
i = 0;
}
void add(Friend a) {
string err = "Out of space";
if ( i == (100 - 1) )
throw err;
friend_list[i] = a;
i++;
}
void print (ostream& f_out) {
for (int j = 0; j < i; j++)
friend_list[j].print(f_out);
}
};
答案 0 :(得分:3)
每个类的构造器(在这种情况下为class Friends
)必须初始化该类的每个字段。
由于Friends()
没有成员初始化程序列表,因此每个字段均为default-initialized(默认情况下)。
对于类,默认初始化只是意味着调用默认构造函数,并且由于Friend
没有默认构造函数(由于具有自定义构造函数,因此不会自动生成),因此编译器不知道如何初始化Friend friend_list[100];
。
另一方面,如果您不提供Friends()
,则编译器会尝试为您生成一个。出于相同的原因,它不能这样做,但是对于隐式生成的构造函数,这不会导致错误。相反,Friends()
被删除(如果您尝试使用它,编译器会告诉您它已删除)。