C++ 为什么这个合成程序要求输入两次值?

C++ 为什么这个合成程序要求输入两次值?,c++,C++,Main.cpp #include <iostream> #include "birthday.h" #include "people.h" using namespace std; int main() { birthday object; people object2; } 生日礼物 #include <iostream> #include "birthday.h" using namespace std; birthday::birthday(

Main.cpp

#include <iostream>
#include "birthday.h"
#include "people.h"
using namespace std;

int main()
{
    birthday object;
    people object2;
}
生日礼物

#include <iostream>
#include "birthday.h"
using namespace std;

birthday::birthday()
{
    cout << "Input date";
    cin >> d;
    cout << "Input month";
    cin >> m;
    cout << "Input year";
    cin >> y;
    cout << d << "/" << m << "/" << y << "\n";
}
void birthday::printdate()
{
    cout << d << "/" << m << "/" << y << "\n";
}
#包括
#包括“生日.h”
使用名称空间std;
生日
{
cout>d;
cout>m;
cout>y;

cout因为您正在创建两个生日对象


一个在您的main中,一个作为People的成员。

生日
的默认构造函数提示用户输入并接受输入。两个生日被实例化

int main()
{
    birthday object; << here
    people object2; << and here
}
解决方案是不接受构造函数中的输入或提供不接受输入的构造函数。我建议如下:

class birthday {
public:
    birthday(int day, int month, int year): 
            d(day),m(month),y(year),
    {
    }

    void printdate();
private:
    int d,m,y; // seriously consider using more descriptive names.
};

输入来自用户,经过验证,然后用于构造
人员
实例,该实例反过来构造
生日

class people {
public:
    people();
private:
    birthday dateofbirth; <<because of here
    std::string x;
};

构造函数中的
告诉编译器a如下。这允许您在进入构造函数体之前构造非平凡的成员,并将参数传递给继承类的构造函数。

您在
生日
类的构造函数中进行输入/输出。您有两个
生日
正在程序中创建的对象

  • int main()函数中
  • 作为
    人员
    对象的成员
  • 您应该考虑将IO工作移到成员函数中,以便在需要时执行IO。

    int main()
    {
       birthday object;
       object.get_input();     //Do your IO
       people object2;
    }
    


    PS:尽可能避免在构造函数中执行IO,这是有原因的例外情况,但对于您自己的用例来说,这只是一个糟糕的设计。就像您有一个
    void birth::printdate()一样
    负责打印日期的成员函数,您应该在类似命名的函数中移动输入操作,如say
    void birth::get_Input()

    main()
    创建一个生日对象,以及一个拥有私有生日对象作为成员的人员对象。换句话说,构造函数运行两次,每个生日对象运行一次。您已经创建了两个此
    类生日
    main中的第一个和
    类人员
    中的第二个对象。您已在构造函数中输入内容,因此它会询问两次用于输入。您可以修改People类构造以获取生日对象,然后对该对象调用print。类似于People(生日对象)。您可以在
    main()中创建
    birth
    两次
    和在
    people.h
    旁白:永远不要要求用户输入系数……这太奇怪了,而且是一种非常糟糕的做法……要求输入,然后使用值作为系数的参数。
    class people {
    public:
        people();
    private:
        birthday dateofbirth; <<because of here
        std::string x;
    };
    
    class birthday {
    public:
        birthday(int day, int month, int year): 
                d(day),m(month),y(year),
        {
        }
    
        void printdate();
    private:
        int d,m,y; // seriously consider using more descriptive names.
    };
    
    class people {
    public:
        people(int day, int month, int year): 
            dateofbirth(day, month, year)
        {
        }
    private:
        birthday dateofbirth;
        std::string x;
    };
    
    int main()
    {
       birthday object;
       object.get_input();     //Do your IO
       people object2;
    }