代码之家  ›  专栏  ›  技术社区  ›  user3326689

在头文件c++[closed]中使用结构

  •  -2
  • user3326689  · 技术社区  · 10 年前

    我在打印头文件中的内容时遇到问题。当我将所有代码都放在一个cpp文件中时,一切都正常,但当我尝试使用头文件时,它不会运行。

    这是我的头文件,兽医

    #ifndef Vet
    #define Vet
    
    class LIST
    {
    private:
        struct PET
        {
            string last_name;
            string pet;
            string animal;
            string color;
            int dob;
    };
    //enter data
    public:
    void Read
    {
        cout<<"Your pets first name: ";
        cin>>PET.pet;
        cin.ignore();
        cout<<"Your last name: ";
        cin>>PET.last_name;
        cin.ignore();
        cout<<"What kind of animal do you have: ";
        cin>>PET.animal;
        cin.ignore();
        cout<<"Your animals dob: ";
        cin>>PET.dob;
        cin.ignore();
        cout<<"Your animals color: ";
        cin>>PET.color;
        cin.ignore();
    }
    };
    #endif
    

    这是我的cpp文件Veterinary.cpp

    //read from header file
    #include <iostream>
    #include <string>
    #include <stdio.h>
    #include <algorithm>
    #include "Vet.h"
    using namespace std;
    int main()
    {
    LIST P;
    
    P.Read();
    
    system("pause");
    return 0;
    }
    
    1 回复  |  直到 10 年前
        1
  •  0
  •   Vlad from Moscow    10 年前

    类没有PET类型的数据成员,因此成员函数Read无效。您需要定义一个PET类型的数据成员,在那里您将输入有关宠物的数据。 C++没有匿名结构。

    还要考虑到,使用命名空间std的指令必须放在具有类定义的头之前。此外,如果您包含标题,效果会更好 <iostream> <string> 并使用限定的标准名称,而不是使用指令。

    标题可能看起来像

    #ifndef Vet
    #define Vet
    
    #include <iostream>
    #include <string>
    
    class LIST
    {
    private:
        struct PET
        {
            std::string last_name;
            std::string pet;
            std::string animal;
            std::string color;
            int dob;
       } pet_data;
    
    //enter data
    public:
        void Read()
        {
            std::cout<<"Your pets first name: ";
            std::cin>>pet_data.pet;
            std::cout<<"Your last name: ";
            std::cin>>pet_data.last_name;
            std::cout<<"What kind of animal do you have: ";
            std::cin>>pet_data.animal;
            std::cout<<"Your animals dob: ";
            std::cin>>pet_data.dob;
            std::cout<<"Your animals color: ";
            std::cin>>pet_data.color;
        }
    };
    
    #endif