为什么看似错误的C++代码编译?

发布于 2025-02-11 05:32:22 字数 1014 浏览 0 评论 0原文

遵循代码编译而不会出错或警告。但是显然,我在实现部分中放了一个额外的Person。这是怎么编译的?实际上,我还尝试将更多的Person放置,但似乎代码几乎是编译。但是,如果使用ONE :: ONE :: PENSE :: SET_NAME,则GCC会发出错误msg。

NM -C Person.o结果:

0000000000000000 T one::Person::set_name(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)

看来编译可以“折叠”类范围,该范围使多个类Person范围范围为单个类范围

CENTOS 8 GCC版本8.5.0 20210514(红帽8.5.0-4)(GCC)

// header file
#include <string>

namespace one {
  class Person {
    public:
      void set_name(const std::string& name);
      void set_age(int age);

    private:
      std::string name_;
      int age_;
  };
}

// implementation
#include "person.h"

// extra Person in the following line.
void one::Person::Person::set_name(const std::string& name) {
  name_ = name;
}

Following code compiles without error or warning. But obviously I put an extra Person in the implementation part. How come this compiles? Actually I also tried to put more Person but it seems the code almost compiles. But if use one::one::Person::set_name, gcc will emit error msg.

nm -C person.o result:

0000000000000000 T one::Person::set_name(std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&)

It seems compile can "fold" class scope, which make multiple class Person scope into a single class scope

Centos 8
gcc version 8.5.0 20210514 (Red Hat 8.5.0-4) (GCC)

// header file
#include <string>

namespace one {
  class Person {
    public:
      void set_name(const std::string& name);
      void set_age(int age);

    private:
      std::string name_;
      int age_;
  };
}

// implementation
#include "person.h"

// extra Person in the following line.
void one::Person::Person::set_name(const std::string& name) {
  name_ = name;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文