【问题标题】:Trying to construct an object with another object as parameter试图用另一个对象作为参数来构造一个对象
【发布时间】:2020-08-13 19:09:11
【问题描述】:

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

【问题讨论】:

  • 我不确定我是否曾在此站点上看到过作为编译器错误的 imgur 链接。
  • 请将错误作为文本包含在问题内(不是通过链接)TIA
  • 您还没有实现任何一个构造函数(已声明但未定义)。
  • 在 C++ 中,尽可能将参数设为const,尤其是作为参考。 string t 复制一份。 const string&amp; t 没有。

标签: c++ class object


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    如果你为Date声明一个默认构造函数,你的问题就解决了:

    #include <iostream>
    #include <string>
    
    using namespace std;
    
    class Date {
        int y, m, 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, string a, string id, Date d) {}
    };
    
    int main() {
        Book Charlie("charlie", "gates", "333H", Date(1, 2, 3));
    
        return 0;
    }
    

    【讨论】:

    • 除了非默认构造函数忽略输入之外,这些肯定是为了初始化类成员。 OP应该prefer initialization lists instead of the constructor body
    • 如果我不想使用默认构造函数怎么办?我将如何通过本书验证日期中的每个变量?
    • @Cluelesshint 简单。使用初始化列表来构造所有的成员变量。
    • @RohanBari 我试过这个..当我尝试创建上面的对象时,默认构造函数没有正确存储日期..我很迷茫如何让它不使用默认值构造
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-06
    相关资源
    最近更新 更多