多态性 - 指向类程序无法编译

L393nd

这个例子来自 C++ in easy steps 5th ed (Mike McGrath) - Ch 8 Polymorphism, "Pointing to Classes"。

我想知道之前是否有人遇到过这个问题,或者知道为什么编译失败。我遵循了书中的示例,由于某种原因,我的程序无法编译并引发与转换相关的异常。我什至在在线 cpp 编译器上尝试过这个并得到了相同的编译器异常,所以这排除了我的编译器。我在 Ubuntu 上使用 g++ 编译器。请参阅附件截图。如果有人可以提供帮助,将不胜感激![指向类屏幕截图]

#include <iostream>
using namespace std;

class Base
{
    public:
     void Identify(int adr) const   
     {
         cout << "Base class called by 0x" << hex << adr << endl;
     }
};

class SubA : public Base {  };
class SubB : public Base {  };

int main()
{
    // create 2 base class pointers each binding to a specific derived class
    Base* ptrA = new SubA;      //or ... SubA a; Base* ptrA = &a;
    Base* ptrB = new SubB;      //or ... SubB b; Base* ptrB = &b;

    // use the pointers to call the base class method, passing the memory address of each for output
    ptrA -> Identify((int) &ptrA); 
    ptrB -> Identify((int) &ptrB);

    return 0;
}

这是抛出的编译器异常:

g++ classptr.cpp -o classptr classptr.cpp:在函数“int main()”中:classptr.cpp:29:26:错误:从“Base**”转换为“int”失去精度[-fpermissive] ptrA ->标识((int) &ptrA);

classptr.cpp:30:26: 错误:从 'Base**' 到 'int' 的转换失去精度 [-fpermissive] ptrB -> Identification((int) &ptrB);

尼克·尤利奇

尝试将此行ptrA -> Identify((int) &ptrA);更改为此ptrA -> Identify((long) &ptrA);

在大多数平台上,指针和长整型的大小相同,但整数和指针在 64 位平台上的大小通常不同。如果将 (Base*) 转换为 (long) 不会丢失精度,则通过将 (long) 分配给 (int),它会正确截断数字以适合。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章