如何解决尝试使用另一个对象作为参数构造一个对象
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;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。