我有一个类声明:
// bar.h
namespace foo {
class bar {
// members both public and private
}
}
当我定义课程时,我想这样做
// bar.cpp
namespace foo::bar {
// member definitions
}
而不是
namespace foo {
bar::x() {}
bar::y() {}
bar::z() {}
}
但我不能。为什么是这样?我认为类声明了命名空间,但我一定是错的。范围运算符是否应该解析命名空间范围,然后是类范围?
我问,因为每当你有一个非平凡长度的类名时,重新输入类名会变得非常重复,特别是如果它有多个成员。也许这就是让人们定义小类接口。
答案 0 :(得分:2)
这是为什么?我认为类声明了名称空间,但我一定是错的
你错了。 :)
范围运算符是否应该解析命名空间范围,然后是类范围?
语言不可能支持这一点,但事实并非如此。
可能是因为它可能会有点混乱,并且因为以下内容会彻头彻尾的谎言:
class bar {
void x();
void y();
void z();
};
namespace bar {
void x() {}
void y() {}
void z() {}
}
实际上,您可以对命名空间进行此类“内联定义”的类比是成员函数的内联定义:
class bar {
void x() {}
void y() {}
void z() {}
};
答案 1 :(得分:2)
首先,您的班级声明后面需要;
:
namespace foo
{
class bar
{
// members both public and private
}; // error without this
}
当您实现类(非内联)时,您可以通过两种方式执行此操作:
void foo::bar::x()
{
// function definition
}
或
namespace foo
{
void bar::x()
{
// function definition
}
}
请注意,bar
是一个类,不是一个名称空间。