为什么不需要在C ++中声明结构体的方法? [英] Why don't methods of structs have to be declared in C++?
问题描述
#include< iostream>
#include< string>
int main()
{
print(Hello!);
}
void print(std :: string s){
std :: cout<< s<<的std :: ENDL;
}
当试图构建它时,我得到以下结果:
program.cpp:在函数'int main()'中:
program.cpp:6:16:error:'print'was没有在此范围内声明
这是合理的。
$ b
struct Snake {
...
Snake(){
...
addBlock(Block(...));
}
void addBlock(Block block){
...
}
void update(){
。 ..
}
} snake1;
我不仅没有收到警告,而且程序实际上编译了!没有错误!这只是结构的性质吗?这里发生了什么事?显然 当编译器看到 在常规的方法情况下,编译器还没有看到声明的类型。 Take, for example, the following code: When trying to build this, I get the following: Which makes sense. So why can I conduct a similar concept in a struct, but not get yelled at for it? Not only do I not get warnings, but the program actually compiles! Without error! Is this just the nature of structs? What's happening here? Clearly A When the compiler sees a In the regular method case, the compiler hasn't yet seen the type declared. 这篇关于为什么不需要在C ++中声明结构体的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! addBlock(Block)
在该方法被声明之前被调用过。 在C ++中,一个 struct 实际上是一个
class
定义,其内容是 public code>,除非另有规定,否则包括protected:或private:section。
class
或 struct
,在对它们进行操作之前,它首先会消化块内的所有声明( {}
)。
#include <iostream>
#include <string>
int main()
{
print("Hello!");
}
void print(std::string s) {
std::cout << s << std::endl;
}
program.cpp: In function ‘int main()’:
program.cpp:6:16: error: ‘print’ was not declared in this scope
struct Snake {
...
Snake() {
...
addBlock(Block(...));
}
void addBlock(Block block) {
...
}
void update() {
...
}
} snake1;
addBlock(Block)
was called before the method was ever declared.struct
in C++ is actually a class
definition where its content are public
, unless specified otherwise by including a protected: or private: section.class
or struct
, it first digests all the declarations within the block ({}
) before operating on them.