我看了几篇文章,这些文章似乎与我在C++入门作业中遇到的问题相似,但仍然找不到解决方案。
我正试图让运营商超载,以增加一个整数。此外,让运营商过载,以增加1的载客量。
请注意,多态性发生在我的类中,我有Ship(基础(、CruiseShip(派生(。
CruiseShip建造商:
CruiseShip::CruiseShip(string name, string year, int passengers) : Ship(name, year)
{
maxPassengers = passengers;
}
操作员过载:
CruiseShip& CruiseShip::operator+(int n) const
{
maxPassengers += n;
return *this;
}
CruiseShip& CruiseShip::operator++() // prefix
{
++maxPassengers;
return *this;
}
CruiseShip CruiseShip::operator++(int) // postfix
{
CruiseShip temp(*this);
operator++();
return temp;
}
Main:
int main()
{
//Create objects, pointers
Ship *ships[3] = {new Ship("Titania", "2020"), new CruiseShip("Lusia", "2029", 200), new CargoShip("Luvinia", "2025", 500)};
//Print out ships
for(Ship *s : ships)
{
s -> print();
cout << endl;
}
//Reset a ships passenger, capacity
//I've tried testing each individually and all 3 still end up with segmentation errors
ships[1] = ships[1] + 5; //segmentation error related to this
ships[1]++; // segmentation error related to this
++ships[1]; // segmentation error related to this
//Print out ships
for(Ship *s : ships)
{
s -> print();
cout << endl;
}
//deallocate
return 0;
}
实现这一功能的方法是使用虚拟函数。但是我们遇到了基类不能返回派生类对象的问题。因此,为了解决这个问题,我们可以简单地让派生类返回基类。下面是一些示例代码:
class Ship
{
public:
Ship(string name, string year)
{
this->name = name;
this->year = year;
}
virtual Ship & operator + (int n)
{
return *this;
}
virtual Ship & operator ++()
{
return *this;
}
virtual Ship & operator ++ (int i)
{
return *this;
}
public:
string name;
string year;
};
class CruiseShip : public Ship
{
public:
virtual Ship& operator+(int n)
{
maxPassengers += n;
return *this;
}
virtual Ship & operator++() // prefix
{
++maxPassengers;
return *this;
}
virtual Ship & operator++(int) // postfix
{
CruiseShip temp(*this);
operator++();
return temp;
}
CruiseShip(string name, string year, int passengers) : Ship(name, year)
{
maxPassengers = passengers;
}
int maxPassengers;
};
在基类和派生类中创建虚拟函数允许有一个定义,无论它是什么类型的船,并且仍然允许我们在派生类中以不同的方式定义虚拟函数。
请注意,CruiseShip超载的运营商返回的是船只,而不是CruiseShip。这满足了具有相同的虚拟函数返回类型的要求。
总的来说,你所要做的唯一改变就是取消引用你的指针,并把这个取消引用的指针放在括号里,如下所示:(*Ship[1])++