为什么不能将不完整的类型转换为void

为什么不能将不完整的类型转换为void

本文介绍了为什么不能将不完整的类型转换为void?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么下面的代码给出以下错误?

Why does the following code give the following error?

为什么要将类型强制转换为void,类型必须完整?

Why does the type need to be complete in order to be casted to void?

struct Incomplete;
class Class
{
    virtual void foo(Incomplete &incomplete)
    {
        (void) incomplete;
        throw std::logic_error("not implemented");
    }
};

错误:

error C2027: use of undefined type 'Incomplete'
    see declaration of 'Incomplete'

推荐答案

这是C和C ++之间的一种更改,Microsoft以前在其中实现了C规则.正如雷米亚贝尔(Remyabel)的回答所指出的那样,此问题已得到解决.

It's a change between C and C++, where Microsoft previously implemented the C rules. As noted in remyabel's answer, that has since been fixed.

在C中,强制转换为void或仅使用表达式本身作为语句(如incomplete;中一样)仍然涉及从左值到右值的转换. C调用它的方式略有不同,但是它是相同的转换.

In C, a cast to void, or simply using an expression as a statement by itself (as in incomplete;), still involves the lvalue-to-rvalue conversion. C calls it slightly differently, but it's the same conversion.

在C ++中,强制转换为void或仅将表达式用作语句本身并不涉及从左值到右值的转换.这是必需的,因为C ++使赋值运算符返回左值,因此,如果应用了左值到右值的转换,则

In C++, a cast to void, or simply using an expression as a statement by itself doesn't involve the lvalue-to-rvalue conversion. This is needed because C++ makes assignment operators return lvalues, so if the lvalue-to-rvalue conversion were applied, then

volatile int i;
i = 1;

不仅可以存储,还可以在之后立即加载.

would not merely store, it would also immediately load afterwards.

从左值到右值的转换需要完整的类型,即使随后丢弃该值也是如此,因为否则将无法知道应读取多少字节.

The lvalue-to-rvalue conversion requires a complete type, even if the value is then discarded, since otherwise, it's impossible to know how many bytes should be read.

这篇关于为什么不能将不完整的类型转换为void?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 05:33