以下代码compiles successfully both with clang++ 5.0.0 and g++ 7.2 (使用 -std=c++17 -Wall -Wextra -Werror -pedantic-errors -O0
编译标志):
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++ 在上面说了什么?
最佳答案
在函数定义中,您不能使用不完整的类型:[dcl.fct]/12 :
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.
但是函数声明 没有这样的限制。当你定义 Bar::get
和 Bar::set
时,Foo
是一个完整的类型,所以程序没问题。
关于c++ - 作为函数参数和返回值的不完整类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47817012/