#include <ostream.h>
Class B
{
public:
virtual void print() const
{
cout << "printB" << std::endl;
}
};
class A
{
public:
virtual void print(const B* b) const
{
cout << "printA" << std::endl;
b->print();
}
};
main()
{
cout << "test" << std::endl;
A* a;
B* b;
a = new A();
b = new B();
a->print(b);
}
Note:
1. the const at the end of the function declaration: indicates that the "this" parameter to the function is const.
2. use the const because it don't modify the object.
本文通过一个C++代码示例展示了如何使用常量指针来避免修改对象,并解释了为什么在某些情况下需要使用const关键字。示例中定义了两个类A和B,类A中的print方法接收一个指向B类型的常量指针。
2619

被折叠的 条评论
为什么被折叠?



