gpt4 book ai didi

c++ - 我们可以通过c++中的运算符重载将一个类的数据转换为另一个类吗?

转载 作者:行者123 更新时间:2023-12-02 10:17:10 24 4
gpt4 key购买 nike

我有2个类EmployeePerson。 Employee类具有nameagesalary三个属性。 Person类具有nameage属性。我想重载赋值运算符,以将Employee类的名称和年龄分配给name和age的人类。

class Employee {
string name;
int age;
float salary;
public:
Employee()
{
name="";
age=0;
salary=0;

}
void operator =(const Employee& a)
{
name=a.name;
age=a.age;
}

};

class Person {
string name;
int age;
public:
Person()
{
name="";
age=0;
}
void display()
{
cout<<"Name are :"<<name<<endl;
cout<<"Age are :"<<age<<endl;
}
};

int main()
{
Employee obj;
person obj1;
obj=obj1;
}

最佳答案

这是上述问题的答案

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

class Employee {
private:
string name;
int age;
float salary;

public:

// default constructor (meaning less)
Employee() {
name = "";
age = 0;
salary = 0.0;
}

// Parameterized constructor
Employee(string name, int age, float salary) {
this->name = name;
this->age = age;
this->salary = salary;
}

// getter members to
// get value of private members
// from outside class
string getName() {
return this->name;
}

int getAge() {
return this->age;
}

float getSalary() {
return this->salary;
}
};
class Person: Employee {
private:
string name;
int age;
public:
Person() {
name = "";
age = 0;
}

void operator = (Employee &emp) {
this->name = emp.getName();
this->age = emp.getAge();
}
void display() {
cout << "Name is : " << name << endl;
cout << "Age is : " << age << endl;
}
};
int main() {
Employee emp("Emp", 25, 45000.00);
Person p1;

p1 = emp;
p1.display();
return 0;

}

关于c++ - 我们可以通过c++中的运算符重载将一个类的数据转换为另一个类吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61551596/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com