为什么没有参数的构造函数似乎是此代码的问题

Why does this Constructor with no arguments seem to be a problem for this code?

本文关键字:代码 问题 似乎是 构造函数 参数 为什么      更新时间:2023-10-16

我无法编译此代码。似乎问题在于朋友班的构造函数,但我不明白问题在哪里。

我试图将其删除,并成功地进行了编译,但是默认的构造函数似乎也无法正常工作。

这是编译器显示的内容:

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);
  }
};

类的每个构造函数(在这种情况下为class Friends(必须初始化该类的每个字段。

由于Friends()没有成员初始化列表,因此每个字段均被默认限制(默认情况下(。

对于类,默认限制仅表示调用默认构造函数,并且由于Friend没有默认的构造函数(由于您具有自定义构造函数,因此不是自动生成的(,因此编译器不知道如何初始化Friend friend_list[100];

另一方面,如果您不提供Friends(),则编译器的attemps为您生成一个。出于相同的原因,它无法这样做,但是对于隐式生成的构造函数,这不会导致错误。相反,Friends()被删除(编译器会告诉您,如果您尝试使用它,则将其删除(。