指向 c++ 中的类对象的指针示例
Example of a pointer to class object in c++
在 main 函数的以下代码中,shape 被声明为指向类 Shape 对象的指针,但类 Rectangle 的对象地址即 rec 保存在下一行中。有人可以告诉我我的理解错在哪里。
class Shape {
protected:
int width, height;
public:
Shape( int a=0, int b=0)
{
width = a;
height = b;
}
int area()
{
cout << "Parent class area :" <<endl;
return 0;
}
};
class Rectangle: public Shape{
public:
Rectangle( int a=0, int b=0)
{
Shape(a, b);
}
int area ()
{
return (width * height);
}
};
class Triangle: public Shape{
public:
Triangle( int a=0, int b=0)
{
Shape(a, b);
}
int area ()
{
return (width * height / 2);
}
};
int main( )
{
Shape *shape;//pointer to Shape class
Rectangle rec(10,7);
Triangle tri(10,5);
shape = &rec;//address of Rectangle class object saved
shape->area();
shape = &tri;
shape->area();
return 0;
}
Shape
需要将area
声明为virtual
以获得多态行为。
virtual int area()
{
...
}
您的代码有几个错误,因此代码没有意义。
例如考虑构造函数
Triangle( int a=0, int b=0)
{
Shape(a, b);
}
首先将调用 Shape 的默认构造函数,因为您没有在 ctor 初始化列表中指定对 Shape 构造函数的调用。因此,默认构造函数会将宽度和高度设置为零。在三角形构造函数的主体中,您只需创建一个永远不会使用的 Shape 类型的临时对象。
它可能看起来很糟糕
Triangle( int a=0, int b=0) : Shape( a, b ) {}
甚至作为
explicit Triangle( int a=0, int b=0) : Shape( a, b ) {}
如果你知道显式的意思。
除此之外,类层次结构应基于虚函数,您可以获得多态的效果。所以类形状应该按以下方式定义
class Shape {
protected:
int width, height;
public:
Shape( int a=0, int b=0) : width( a ), height( b ) {}
virtual ~Shape() {}
virtual int area() const = 0;
};
int Shape::area() const
{
cout << "Parent class area :" <<endl;
return 0;
}
并根据这些更改对派生类进行日期处理。
Rectangle
派生自Shape
,见行
class Rectangle: public Shape
这称为继承或"是"关系:Rectangle
是Shape
。因此,Shape*
可以指向矩形。例如,可以在基类指针与继承的类指针中找到更多信息吗?或大多数C++涵盖继承的教程。
然而,正如 Roddy 的回答所指出的,你应该在 Shape
中声明area
为 virtual
,否则调用 shape->area()
将始终调用Shape
的 area
方法,而不是 Rectangle
提供的覆盖方法。由于area
for Shape
并没有真正的意义,您甚至可以考虑将其声明为纯虚拟:
virtual int area() = 0;
相关文章:
- 为什么指针对象没有调用默认构造函数
- 如何访问双指针对象中的方法
- 如何使用智能指针对象执行成员函数指针
- 调用带有指针对象错误的指针变量
- 如何从模板类重载创建的指针对象上的运算符?
- C++指针对象的运算符重载
- 如何初始化数组指针对象
- 如何打印出唯一指针对象向量中的值(基于范围的循环)?C++
- C++指针对象差异
- 涉及继承,指针对象的交易以及何时进行的问题
- 表达式必须在C 中具有指针对象类型
- 下标需要数组或指针类型表达式必须具有指针对象类型
- 字符指针对象和相应的字符数组元素比较
- 如何在 c++ 中克隆为弱指针对象
- 指针对象使用CPP中的指针表达式进行比较
- Visual Studio中智能指针对象的自定义视图
- 使用指针 /对象 /模板参数正确构成
- 如果我确定只有一个线程一次处理指针/对象,则C/C 仍应使用同步
- 如何将值分配给指针对象 c++
- 更改智能指针对象,然后访问它