虚函数可以设置基类的公共数据成员
Virtual Functions can set publicdata members of base class?
setPosition(3,4) 在方法 foo() 中工作,但在派生的虚拟绘制方法中不起作用矩形类。 这不是C++中的功能吗?谢谢。
class Shape
{
public:
int posX, posY;
public:
virtual void draw() const = 0;
void setPosition(int pX, int pY)
{
posX = pX;
posY = pY;
}
};
class Rectangle : public Shape
{
public:
virtual void draw() const
{
cout << "Drawing rectangle at " << posX << " "
<< posY << endl;
setPosition(3,4);
}
void foo()
{
setPosition(3,4);
}
};
不能从const
方法调用非const
方法,因为这不会使对象保持不变。
如果draw
需要调用setPosition
并因此更改Rectangle
,则不能将其声明为const
。
相关文章:
- 如何在c++中定义以struct为数据成员的类中的构造函数
- 枚举不是非静态数据成员或类的基类
- 通过使用具有私有数据成员的类重载 + 运算符来添加分数
- 是否有必要重载具有另一个类 B 的数据成员的类 A 的赋值运算符和复制构造函数?
- 指向成员的 C++ 指针(指向成员基类的指针)
- 如何创建一个将队列作为数据成员的类,该成员在 c++ 中存储另一个类的实例
- 没有任何数据成员的类会导致内存泄漏吗?
- 使用 #include 按<algorithm>字符串数据成员对类对象的向量进行排序
- 从私有结构数据成员访问类公共成员函数C++
- 向下转换为没有数据成员"foreign"类
- 为具有一个数字数据成员的类定义所有比较运算符的方便方法
- 错误:非整型 'const char[]' 的静态数据成员的类内初始化无效
- 运算符重载与 C++ : 具有指针数据成员的类
- 作为另一个类的数据成员的类
- 如何将具有相同类型的不同矢量数据成员的类对象传递给可以对这些数据成员中的任何一个进行操作的函数
- 当我们对没有任何数据成员的类的对象使用sizeof运算符时.那么输出会是什么
- 如何在c++中处理具有不同类型的多个数据成员的类
- 复制具有shared_ptr数据成员的类的构造函数
- 用于具有const数据成员的类的move和右值赋值操作符
- 英特尔C++错误:"pair"不是非静态数据成员或类"std::pair<const int, double>"的基类