![](/img/trans.png)
[英]How does one call an overloaded method from a child class from a parent class variable in C++
[英]How to call child class method from parent class in c++
是否可以从父 class 访问子 class 方法以及如何访问? 例如我有这个代码:
城市.cc:
City::City(unsigned int M, unsigned int N)
{
this->M = M;
this->N = N;
for(unsigned int i = 0; i < M; i++)
{
for(unsigned int j = 0; j < N; j++)
{
Cell cell = Cell();
matrix[i][j] = &cell;
}
}
}
int City::getResidentCapacity()
{
int total_capacity = 0;
for(unsigned int i = 0; i < M; i++)
{
for(unsigned int j = 0; j < N; j++)
{
if(matrix[i][j]->selfType() == "Residential")
{
total_capacity += matrix[i][j]->getResidentCapacity();
}
}
}
return total_capacity;
}
单元格.hh:
#pragma once
#include <string>
using namespace std;
class Cell
{
private:
float price;
float electricity;
public:
Cell(float price, float electricity);
Cell();
float getElectricity();
float getPrice();
virtual string selfType();
};
细胞.cc:
#include "Cell.hh"
Cell::Cell(float price, float electricity) : price(price), electricity(electricity) {}
Cell::Cell() : price(0), electricity(0) {}
float Cell::getElectricity()
{
return electricity;
}
float Cell::getPrice()
{
return price;
}
住宅.hh:
#pragma once
#include "Cell.hh"
class Residential : public Cell
{
private:
float price = 1;
float electricity = 1;
int residentCapacity;
public:
Residential(float price, float electricity) : Cell(price, electricity) {}
int getResidentCapacity();
string selfType();
};
住宅.cc:
#include "Residential.hh"
string Residential::selfType()
{
return "Residential";
}
int Residential::getResidentCapacity()
{
return residentCapacity;
}
当我尝试运行代码时,出现以下错误:
City.cc:在成员 function 'int City::getResidentCapacity()':City.cc:88:38:错误:'class Cell' 没有名为'getResidentCapacity'的成员 88 | 总容量 += 矩阵[i][j]->getResidentCapacity();
我该如何解决?
鉴于 class Fruit
:
class Fruit
{
public:
virtual void print_name();
};
还有一个孩子:
class Orange : public Fruit
{
public:
void print_name()
{ std::cout << "Orange\n"; }
bool is_citrus() const { return true; }
};
如果我们希望父 class Fruit
调用Orange::is_citrus
,那将无法正常工作,因为父不知道是否有任何子,但也不知道子的任何方法。
因此,一种解决方案是在父 class 中创建一个虚拟 function ,子 class 可以实现:
class Fruit
{
public:
virtual bool has_a_peel() = 0;
virtual void print_name();
virtual void details()
{
if (has_a_peel())
{
std::cout << "peel the fruit before eating.\n";
}
}
};
class Orange : public Fruit
{
public:
void print_name()
{ std::cout << "Orange\n"; }
bool is_citrus() const { return true; }
bool has_a_peel()
{ return true; }
};
在上面的代码中,Parent class Fruit
可以调用 child class has_a_peel
。
提醒:使用这种技术,所有子类都必须实现has_a_peel
class。 您可以从has_a_peel()
方法中删除“= 0”,这意味着并非所有孩子都需要实现它。 但如果孩子这样做了怎么办?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.