类型不完整的函数参数和返回值 [英] Incomplete types as function parameters and return values

查看:223
本文介绍了类型不完整的函数参数和返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码使用 clang ++ 5.0.0 g ++ 7.2成功编译 (带有-std=c++17 -Wall -Wextra -Werror -pedantic-errors -O0编译标志):

The following code compiles successfully both with clang++ 5.0.0 and g++ 7.2 (with the -std=c++17 -Wall -Wextra -Werror -pedantic-errors -O0 compilation flags):

struct Foo;

struct Bar
{
    Foo get() const;

    void set(Foo);
};

struct Foo
{
};

Foo Bar::get() const
{
    return {};
}

void Bar::set(Foo)
{
}


int main()
{
    Bar bar{};

    (void)bar.get();
    bar.set(Foo{});
}

使用不完整的类型作为函数参数和返回值是否有效? C ++在上面怎么说?

Is it valid to use incomplete types as function parameters and return values? What does the C++ say on it?

推荐答案

在函数定义中,不能使用不完整的类型:

In a function definition, you cannot use incomplete types: [dcl.fct]/12:

在函数定义的上下文中,参数的类型或函数定义的返回类型不应是不完整的(可能是 cv 限定的)类类型,除非删除了该函数. /p>

The type of a parameter or the return type for a function definition shall not be an incomplete (possibly cv-qualified) class type in the context of the function definition unless the function is deleted.

但是函数 declaration 没有这样的限制.在定义Bar::getBar::set时,Foo是完整类型,因此程序很好.

But a function declaration has no such restriction. By the time you define Bar::get and Bar::set, Foo is a complete type, so the program is fine.

这篇关于类型不完整的函数参数和返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆