【问题标题】:Type of Base class pointer pointing to derived class object指向派生类对象的基类指针类型
【发布时间】:2014-06-16 06:05:31
【问题描述】:

指向派生类对象的基类指针的类型会改变吗?

如果我有类似的东西:

class base{
public:
    int a;
    void doit();
};

class derived : public base {
public:
    int a,b;
    void doit();
}

然后我做以下作业:

base *b = new derived;
cout << typeof(b); 

指针 b 的类型会更改为 派生指针 还是保持不变,即 指向基址的指针?为什么?

【问题讨论】:

  • 它应该给出一个编译器错误,你没有从基类继承派生。
  • 假设继承正确,b 的类型应该是基类,而不是派生类。因为 type 意味着指针的类型(它是 base*),而不是它指向的对象的类型。
  • 请注意 typeof 不是标准的。你是说typeid吗?
  • 对不起,我忘了继承基类。

标签: c++ inheritance typeinfo


【解决方案1】:

代码应该是这样的:

          class A
          {};

         class B:public A
         {};


         int main()
         {

           A* a= new B();

           cout<<typeid(a).name()<<endl;
        }

输出:A* 类。

因为 type 意味着指针的类型(它是 base*),而不是它指向的对象的类型。

【讨论】:

    猜你喜欢
    • 2021-07-02
    • 2021-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 1970-01-01
    相关资源
    最近更新 更多