类和继承

Classes and inheritance

本文关键字:继承      更新时间:2023-10-16

我是OOP的新手,在编写第一段代码时遇到了一个问题。我不明白为什么我不能把一个类作为另一个类的一部分。不,我不希望那个类继承另一个。其中一个要求是我要防止对象复制。

#pragma once
#include<iostream>
#include<string>
using namespace std;
class Pilot 
{
public:
Pilot(/*string x*/) 
{
setName();
flight_hours = 0;
set_status(0);
}
void setName(/*string x*/) 
{
cout<<"Unesi ime pilota: ";
getline(cin,name);
}
string getName() 
{
return name;
}
void increase_flight_hours(int n) 
{
flight_hours += n;
}
int get_flight_hours() 
{
return flight_hours;
}
void set_status(bool b) 
{
status;
}
bool get_status() 
{
return status;
}
void display_pilot() 
{
cout << name;
cout << "(", flight_hours, ")";
if (status)
cout << "-L" << endl;
else
cout << "-N" << endl;
}
Pilot (const Pilot&) = delete;
void operator=(const Pilot&) = delete;
private:
string name;
int flight_hours;
bool status;


};

#pragma once
#include"Pilot.h"
class Avion 
{
public:
Avion ()
{
setName();
set_capacity();
}
void setName(/*string x*/)
{
cout << "Unesi ime aviona: ";
getline(cin, name);
}
string getName()
{
return name;
}
void set_capacity()
{
cout << "Unesite kapacitet aviona: ";
cin >> capacity;
}
int get_capacity() 
{
return capacity;
}
Pilot get_captain() 
{
return captain;
}
private:
string name;
Pilot captain;
Pilot copilot;
int capacity;
};

我收到以下错误:function "Pilot::Pilot(const Pilot &)" (declared at line 50 of "C:UsersmjovasourcereposProject1Project1Pilot.h") cannot be referenced -- it is a deleted function Project1 C:UsersmjovasourcereposProject1Project1Planes.h 36

这里有一个问题:

Pilot get_captain() 
{
return captain;
}

它返回队长的副本,并且您已明确禁止复制。

返回常量引用:

const Pilot& get_captain() 
{
return captain;
}

(不要试图复制它返回的内容(。

在"Planes.h"中也可能有其他一些与复制相关的代码;尚不清楚CCD_ 2是否在该文件中定义。

附带说明:由于无法复制Pilots,因此Avioncaptaincopilot成员存在问题(例如,无法实现set_captain(
我怀疑你将来会想把它们变成指针,让飞行员在没有飞机的情况下生存,反之亦然。