尝试使用另一个对象作为参数构造一个对象

问题描述

https://imgur.com/gallery/pEw8fBs https://pastebin.com/xvWFHrTU

我的错误已在上方发布..我不明白这段代码有什么问题..我正在尝试构造一本带有日期对象的书。请帮助,这也是我的第一篇文章! :)

#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<cmath>
using namespace std;
inline void keep_window_open() { char ch; cin >> ch; }

class Date {
    int y,m,d;

public:
    Date(int d,int m,int y);
};

class Book {
    string title;
    string author;
    string isbn;
    Date date;

public:
    Book(string t,string a,string id,Date d);
};

int main() {
    Book Charlie("charlie","gates","333H",Date(1,2,3));
}

解决方法

两个构造函数都已声明但未定义

class Date {
    int y,m,d;

public:
    Date(int _d,int _m,int _y) : y(_y),m(_m),d(_d) {} // definition
};

class Book {
    string title;
    string author;
    string isbn;
    Date date;

public:
    Book(string t,string a,string id,Date d)
    : title(t),author(a),isbn(id),data(d) {} // definition
};
,

如果您为Date声明默认构造函数,您的问题将得到解决:

#include <iostream>
#include <string>

using namespace std;

class Date {
    int y,d;

public:
    // Default constructor which will be used in 'Book'
    Date() {}
    // Don't semicolon here,just two braces required
    Date(int d,int m,int y) {}
};

class Book {
    string title;
    string author;
    string isbn;
    // Default constructor called here
    Date date;

public:
    // You can code everything inside the braces now
    // NOTE 2: Default constructor called here
    Book(string t,Date d) {}
};

int main() {
    Book Charlie("charlie","gates","333H",Date(1,2,3));

    return 0;
}