小编G M*_*ann的帖子

在C++中使用'static_cast'进行向下转换

考虑:

class base
{
    base();
    virtual void func();
}

class derived : public base
{
    derived();
    void func();
    void func_d();
    int a;
}


main
{
    base *b = new base();
    sizeof(*b); // Gives 4.
    derived * d = static_cast<derived*>(b);
    sizeof(*d); // Gives 8- means whole derived obj size..why?
    d->func_d();
}
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,我做了一个基指针的向下转换,它指向基对象到派生类指针.我想知道派生指针如何具有整个派生类对象.我可以调用派生类函数(仅在派生类中声明).我没有在这里得到这个概念.

c++

14
推荐指数
3
解决办法
2万
查看次数

通过解除引用NULL指针来分配引用

int&  fun()
{
    int * temp = NULL;
    return *temp;
}
Run Code Online (Sandbox Code Playgroud)

在上面的方法中,我试图取消引用NULL指针.当我调用此函数时,它不会给出异常.我发现当返回类型是引用时它不会给出异常,如果它是按值,那么它.即使将NULL指针的解引用引用为引用(如下面的行),它也不会给出.

int* temp = NULL:
int& temp1 = *temp;
Run Code Online (Sandbox Code Playgroud)

在这里我的问题是,在引用的情况下编译器是否进行解除引用?

c++ pointers reference null-pointer undefined-behavior

12
推荐指数
2
解决办法
5451
查看次数

静态成员变量文件范围

静态变量在该文件中的范围仅在声明它们的位置,如下面的代码所示:

file1-

static int a;
Run Code Online (Sandbox Code Playgroud)

file2-

extern int a;
Run Code Online (Sandbox Code Playgroud)

这将给出链接错误,因为静态变量a仅在file1中具有范围.但我对以下代码感到困惑:

file2-

#include "file1"
extern int a;
Run Code Online (Sandbox Code Playgroud)

这里不会给出任何链接错误.然后它意味着编译器引用在file1中声明的"a".但是当你调试时,你会发现变量"a"的地址在file1和file2中是不同的.编译器是否在file2中创建另一个全局变量"a"?

完整代码 -

文件temp1.h -

static int w = 9;

class temp1 
{
public:
   temp1(void);
public:
   ~temp1(void);

   void func();

};
Run Code Online (Sandbox Code Playgroud)

........................ CPP .................

temp1::temp1(void)
{
   int e =w;
}

temp1::~temp1(void)
{
}
void temp1::func()
{
}
Run Code Online (Sandbox Code Playgroud)

....................................... file2-

#include "temp1.h"

extern int w;
int _tmain(int argc, _TCHAR* argv[])
{
   w  = 12;

   temp1 obj;
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

这里当我调试并检查temp1构造函数和file2中的值和地址是不同的.

c++

3
推荐指数
1
解决办法
1772
查看次数