首页 > 解决方案 > 在c ++中使用struct,无法解决问题

问题描述

这就是我想要做的:

实现一个结构Employee。一个雇员有一个名字(一个 char )和一个薪水(一个 double)。编写一个默认构造函数,一个带有两个参数(姓名和薪水)的构造函数,以及方法 char getName() double getSalary() 以返回姓名和薪水。编写一个小的全局函数 TestEmployee() 来测试你的结构。

这就是我到目前为止所做的:

#include<iostream>
#include<cstring>
using namespace std;

//Implement a structure Employee.
struct Employee
{
private:
    //An employee has a name (a char *) and a salary (a double).
    char *EmpName;
    double EmpSalary;
public:
    //default constructor
    Employee()
    {
        this->EmpName = new char[100];
        this->EmpSalary = 0.00;
    }
    //a constructor with two parameters (name and salary),
    Employee(char* name_, double salary_)
    {
        do
        {
            this->EmpName = name_;
            this->EmpSalary = salary_;
        
        }while(salary_<0);
    }
    //char* getName() to return the name
    char* getName()
    {
        return this->EmpName;
    }
    //double getSalary() to return the salary.
    double getSalary()
    {
        return this->EmpSalary;
    }
};

//Write a small global function TestEmployee() to test your structure.
void TestEmployee()
{
    //Employee employee_;
    char* empName = new char[100];
    double empSalary;

    cout<<"Creating a new employee.\nPlease type the name:"<<endl;
    cin>>empName;
    cout<<"Please specify the salary:"<<endl;
    cin>>empSalary;
    cout<<"New employee has been created."<<endl;

    Employee employee_(empName, empSalary);

    cout<<"Name of employee: "<<endl;
    cout<<employee_.getName()<<endl;
    cout<<"Salary: "<<endl;
    cout<<employee_.getSalary()<<endl;
    cout<<"Thank you for testing structure Employee."<<endl;
}
int main()
{
    TestEmployee();
}

我似乎找不到错误,这个程序不工作。这是它给出的输出:

在此处输入图像描述

当这是它应该具有的输出时:

在此处输入图像描述

标签: c++functionpointersstructreference

解决方案


推荐阅读