对指针的引用-多态性
Reference to a pointer - Polymorphism
如果我不是在将基指针发送给另一个类构造函数时使用对指针的引用- 和在该类中将basepointer绑定到基的派生对象- basepointer返回NULL。
简单地说——这是什么原因?
#include <iostream>
using namespace std;
class Base {
public:
virtual void print() = 0;
};
class Sub1 : public Base {
public:
void print() {
cout << "I am allocated!n";
}
};
class App {
public:
App(Base *b) {
b = new Sub1;
}
};
int main() {
Base *b;
b = NULL;
App app(b);
if (b != NULL)
b->print();
else
cout << "Basepointer is NULLn";
return 0;
}
这里的关键部分是app类构造函数的签名
当不使用对基指针的引用时,即
App(Base *b)
输出为:
Basepointer is NULL
当使用对基类的引用时,即
App(Base *&b)
输出为:
I am allocated!
您通过值传递指针,这意味着值被复制了,并且在函数中您只修改了副本。修改副本当然不会修改原始文件
相关文章:
- 多态性和功能结合
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 使用取消引用的指针的多态性会产生意外的结果.为什么?
- C++boost序列化多态性问题
- 如何查找哪个类对象位于数组的特定索引上(多态性)
- 如何在多线程中正确使用unique_ptr进行多态性?
- 具有智能指针的多态性
- 多态性和共享_ptr通过引用传递
- C++多态性,关于宣布对派生类的基础类引用
- 收到未定义的引用错误 c++ 继承/多态性
- 具有引用成员变量的多态性
- 具有引用数据类型的函数多态性
- 带有引用的多态性没有按预期运行
- 多态性在没有指针/引用的C++中工作吗
- 使用具有多态性的引用时初始化无效
- C++中的多态性不能与引用一起正常工作
- 为什么不能将多态性与值一起使用,而是引用和指针
- 成员变量多态性和参数引用
- 对指针的引用-多态性
- 对引用使用多态性.非const引用的无效初始化