为什么不需要在C ++中声明结构体的方法? [英] Why don't methods of structs have to be declared in C++?

查看:195
本文介绍了为什么不需要在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;

我不仅没有收到警告,而且程序实际上编译了!没有错误!这只是结构的性质吗?这里发生了什么事?显然 addBlock(Block)在该方法被声明之前被调用过。 在C ++中,一个 struct 实际上是一个 class 定义,其内容是 public code>,除非另有规定,否则包括protected:或private:section。

当编译器看到 class struct ,在对它们进行操作之前,它首先会消化块内的所有声明( {} )。



在常规的方法情况下,编译器还没有看到声明的类型。


Take, for example, the following code:

#include <iostream>
#include <string>

int main()
{
    print("Hello!");
}

void print(std::string s) {
    std::cout << s << std::endl;
}

When trying to build this, I get the following:

program.cpp: In function ‘int main()’:
program.cpp:6:16: error: ‘print’ was not declared in this scope

Which makes sense.

So why can I conduct a similar concept in a struct, but not get yelled at for it?

struct Snake {
    ...

    Snake() {
        ...
        addBlock(Block(...));
    }

    void addBlock(Block block) {
        ...
    }

    void update() {
        ...
    }

} snake1;

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 addBlock(Block) was called before the method was ever declared.

解决方案

A struct in C++ is actually a class definition where its content are public, unless specified otherwise by including a protected: or private: section.

When the compiler sees a class or struct, it first digests all the declarations within the block ({}) before operating on them.

In the regular method case, the compiler hasn't yet seen the type declared.

这篇关于为什么不需要在C ++中声明结构体的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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