C++重复了类类型的定义

C++ repeated definitions of class types?

本文关键字:类型 定义 C++      更新时间:2023-10-16

下午好!

如果这个问题看起来很模糊,很抱歉,但这里有一些(不完整的)上下文代码。具体来说,这是关于"UserInfo-inputInfo"定义部分的,如实现文件中的函数UserInfo::setUserInfo()和UserInfo::displayProfile()中所示。

project02.cpp(实现文件)

#include <iostream>
#include "project02.h"
using namespace std;
void UserInfo::setUserInfo()
{
    UserInfo inputInfo;
    string fName;
    string lName;
    int bYear;
    string city;
    string occupation;
    cout << "Please enter your first name: ";
    cin >> fName;
    inputInfo.setFirstName(fName);
    cout << "Please enter your last name: ";
    cin >> lName;
    inputInfo.setLastName(lName);
    cout << "You are now registered as: " << inputInfo.getFirstName() << " " << inputInfo.getLastName();
}
void UserInfo::displayProfile()
{
    UserInfo inputInfo;
    cout << "Profile Information:" << endl;
    cout << "Name: " << inputInfo.getFirstName() << " " << inputInfo.getLastName();
}
void UserInfo::setFirstName(string fName)
{
    _firstName = fName;
}
string UserInfo::getFirstName()
{
    return _firstName;
}
void UserInfo::setLastName(string lName)
{
    _lastName = lName;
}
string UserInfo::getLastName()
{
    return _lastName;
}

project02.h(头文件)

#ifndef PROJECT02_H
#define PROJECT02_H
using namespace std;
class UserInfo
{
    public:
        string getFirstName();
        void setFirstName(string first);
        string getLastName();
        void setLastName(string last);
        int getBirthYear();
        void setBirthYear(int year);
        string getCurrentCity();
        void setCurrentCity(string city);
        string getOccupation();
        void setOccupation(string occ);
        void setUserInfo();
        void displayProfile();
    private:
        string _firstName;
        string _lastName;
        int _birthYear;
        string _currentCity;
        string _occupation;
};
#endif // PROJECT02_H

project02main.cpp(主文件)

#include <iostream>
#include "project02.h"
using namespace std;
int main()
{
    UserInfo inputInfo;
    inputInfo.setUserInfo();
    return 0;
}

现在的问题是:除了在实现文件中每次为不同的函数重复定义对象"UserInfo inputInfo;"之外,还有其他选择吗?

此时不要在该数据类型的方法中创建相同数据类型的对象-只需调用setFirstname()和getFirstname。