为什么我的基类指针变量不能访问派生类中的函数?
Why can't my base class pointer variable access functions from the derived class?
class Polygon {
protected:
int width, height;
public:
void set_values (int a, int b)
{ width=a; height=b; }
};
class Rectangle: public Polygon {
public:
int area()
{ return width*height; }
};
int main () {
Rectangle rect;
Polygon * ppoly1 = ▭
ppoly1->set_values (4,5);
cout << rect.area() << 'n';
return 0;
}
在上面的例子中,ppoly1 指向什么,这个指针如何无法访问矩形类的函数?
为什么 ppoly1->area() 是一个错误
谢谢!
表达式 ppoly1->area()
是一个错误,因为ppoly1
被键入到没有声明area
方法的Polygon
。 当C++尝试评估此成员时,它基本上从 Polygon
开始,没有看到名为area
的成员,因此发出错误
听起来您想为Polygon
类型提供没有实现的area
方法的概念(强制派生类型提供一个)。 如果是这种情况,那么您应该在Polygon
中声明一个未实现的虚拟方法
class Polygon {
...
virtual ~Polygon() { }
virtual int area() = 0;
};
基类对其派生类一无所知。定义基类时,尚无任何派生类。
变量 ppoly1 的类型为 Polygon *。类多边形没有方法区域,因此编译器会发出错误。
如果要对派生类使用公共接口,则应在基类中声明它。例如
class Polygon {
protected:
int width, height;
public:
void set_values (int a, int b)
{ width=a; height=b; }
virtual int area() const = 0;
virtual ~Polygon(){}
};
class Rectangle: public Polygon {
public:
int area() const
{ return width*height; }
};
int main () {
Rectangle rect;
Polygon * ppoly1 = ▭
ppoly1->set_values (4,5);
cout << rect.area() << 'n';
return 0;
}
ppoly1
是一个多边形指针。指针指向 Rectangle 对象这一事实并不使它能够调用 Rectangle 函数;类型仍Polygon*
.若要使其能够调用矩形函数,需要使其成为矩形指针,或在 Polygon 类中实现虚拟方法,
例如
virtual int area() const;
这意味着当 Polygon 对象area()
调用它时,它将查找派生最多的 area()
实例。ppoly1
,这将是Rectangle->area()
.您可以保持Rectangle
代码与以前相同。
关于虚拟功能的维基百科:http://en.wikipedia.org/wiki/Virtual_function
相关文章:
- 为什么使用 "this" 指针调用派生成员函数?
- 在派生函数中指定void*参数
- 如何通过派生类函数更改基类中的向量
- 如何委托派生类使用其父构造函数?
- 如何使用单独文件中的派生类访问友元函数对象
- 使用基类指针创建对象时,缺少派生类析构函数
- 在 C++ 中用派生类型重写成员函数
- 用常见虚拟函数实现的任意组合来实现派生类的正确方法是什么
- 如果基类包含双指针成员,则派生类的构造函数
- 有没有比在库中添加一个并非由所有派生类实现的新虚拟函数更好的设计实践
- 在派生类中绑定非静态模板化成员函数
- 使用 std::variant<...时调用 BaseState 函数而不是派生函数>
- C++:为什么无法在派生类中访问受保护的构造函数?
- C++派生的类构造函数
- C++重载函数,一个采用基类的参数,另一个采用派生类的参数
- C ++如何在原始抽象类中创建一个函数,该函数接受派生类的输入
- 覆盖虚拟函数 - 派生类具有不同的参数
- 正在调用基方法,而不是从构造函数派生方法
- 从具有相同虚拟函数的父函数派生时如何调用子函数
- 从派生类对象调用基类函数.派生类构造函数中设置的基类数据成员