为什么看似错误的C++代码编译?
遵循代码编译而不会出错或警告。但是显然,我在实现部分中放了一个额外的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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论