本文介绍了为什么我的班级的规模为零?如何确保不同的对象具有不同的地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个类,但它的大小为零。现在,如何确保所有对象具有不同的地址? (我们知道,空类的大小非零。)

I created a class but its size is zero. Now, how can I be sure that all objects have different addresses? (As we know, empty classes have a non-zero size.)

#include<cstdio>
#include<iostream>
using namespace std;
class Test
{
    int arr[0];//Why is the sizezero?
};

int main()
{
    Test a,b;  
      cout <<"size of class"<<sizeof(a)<<endl;
       if (&a == &b)// now how we ensure about address of objects ?
          cout << "impossible " << endl;
       else
          cout << "Fine " << endl;//Why isn't the address the same? 

        return 0;
}        


推荐答案

C ++不允许在任何上下文中大小为 0 的数组声明。但是,即使你使你的类定义完全空, sizeof 仍然需要评估为非零值。

Your class definition is illegal. C++ does not allow array declarations with size 0 in any context. But even if you make your class definition completely empty, the sizeof is still required to evaluate to a non-zero value.

换句话说,如果你的编译器接受类定义,并将上面的 sizeof 归零,那么该编译器超出了标准C ++语言的范围。它必须是与标准C ++无关的编译器扩展。

In other words, if your compiler accepts the class definition and evaluates the above sizeof to zero, that compiler is going outside of scope of standard C++ language. It must be a compiler extension that has no relation to standard C++.

因此,在这种情况下,唯一的答案是为什么问题是:因为这是它的方式是在你的编译器中实现的。

So, the only answer to the "why" question in this case is: because that's the way it is implemented in your compiler.

我没有看到它与确保不同的对象具有不同的地址有关。无论对象大小是否为零,编译器都可以轻松实施此操作。

I don't see what it all has to do with ensuring that different objects have different addresses. The compiler can easily enforce this regardless of whether object size is zero or not.

这篇关于为什么我的班级的规模为零?如何确保不同的对象具有不同的地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 10:03