gpt4 book ai didi

c++ - 在 C++ 中的类函数下在自身中包含一个类

转载 作者:行者123 更新时间:2023-11-28 01:18:50 25 4
gpt4 key购买 nike

此代码编译正常并输出 10,但我不确定为什么?

#include <iostream>

class test1 {
public:
int getId(){
test1 t;
return t.getAnotherId();
}
int getAnotherId(){
return 10;
}
};

int main(){
test1 t;
std::cout << t.getId() << std::endl;
return 0;
}

getId() 下调用时,test1 是否已完全定义?

我问是因为我知道这是无效的,因为类还没有完全定义:

class Node {
char *cargo;
Node left;
Node right;
}

最佳答案

来自规范的 9.2.2:

A class is considered a completely-defined object type (3.9) (or complete type) at the closing } of the class- specifier. Within the class member-specification, the class is regarded as complete within function bodies, default arguments, using-declarations introducing inheriting constructors (12.9), exception-specifications, and brace-or-equal-initializers for non-static data members (including such things in nested classes). Otherwise it is regarded as incomplete within its own class member-specification.

所以在方法体内,类是完整的,可以作为一个完整的类型使用(所以你可以定义一个类类型的局部)。

关于c++ - 在 C++ 中的类函数下在自身中包含一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57667042/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com