【发布时间】:2016-02-15 06:10:53
【问题描述】:
有没有一种方法可以将作用域限定为特定类的方法分组,而无需每次都使用作用域运算符 ::?冒着引起某些人鄙视的风险,我可以粗略地类比一下 JavaScript with 声明;但是,这里是在源码中使用,并没有执行。
一个简化的示例:想象一个Cheese 类,其中weigh、shred 和melt 函数声明如下:
class Cheese {
public:
Cheese();
... // other constructors, copy, etc.
~Cheese();
int weigh();
int shred();
int melt();
}
典型的函数定义如下:
Cheese::Cheese() { //constructor stuff };
... // other constructors, copy, etc.
Cheese::~Cheese() { //destructor stuff };
int Cheese::weigh() { return weighed; }
int Cheese::shred() { return shredded; }
int Cheese::melt() { return melted; }
有没有办法说,“嘿编译器,所有这些定义都在Cheese 类的范围内。”
也许是这样?
scope::Cheese {
Cheese() { //constructor stuff };
... // other constructors, copy, etc.
~Cheese() { //destructor stuff };
int weigh() { return weighed; }
int shred() { return shredded; }
int melt() { return melted; }
}
或者,
Cheese:: {
Cheese() { //constructor stuff };
... // other constructors, copy, etc.
~Cheese() { //destructor stuff };
int weigh() { return weighed; }
int shred() { return shredded; }
int melt() { return melted; }
}
【问题讨论】:
-
没有。不确定如何处理模板化的奶酪,即使有。
-
不管怎样,我认为这是 C++ 中最愚蠢/最烦人的方面之一。
-
@xaxxon 为什么模板会成为问题?
-
也许不是......但通过 ClassName::method_name 来搜索定义的能力确实非常方便 - 比不再输入类名更重要......
-
您仍然可以在建议的系统中进行搜索。你会在第一个命题中点击
scope::Cheese语句;第二个中的Cheese::文本。 ~kjm~