是否有一种方法可以避免在实现文件中重复执行Graph::
,但仍将类拆分为标头+实现?如在:
头文件:
#ifndef Graph_H
#define Graph_H
class Graph {
public:
Graph(int n);
void printGraph();
void addEdge();
void removeEdge();
};
#endif
实施文件:
Graph::Graph(int n){}
void Graph::printGraph(){}
void Graph::addEdge(){}
void Graph::removeEdge(){}
我猜这是为了避免很多“不必要的输入”。可悲的是,没有办法摆脱范围(许多其他答案都告诉过您),但是我个人要做的是将所有函数原型定义的类放在漂亮的行中,然后将其复制/粘贴到实现文件中,然后按ctrl-c您的ClassName ::在剪贴板上,并使用ctrl-v运行该行。
不幸的是,如果要避免在printGraph,addEdge等前面键入“ Graph ::”,那么答案是“否”。在C ++中无法访问类似于C#的“部分类”功能,并且任何类的名称(例如“ Graph”)都不是名称空间,而是一个范围。
不,没有。至少不是直接的。您可以尝试使用预处理器技巧,但不要这样做。
#define IMPL Graph::
IMPL Graph(int n){}
void IMPL printGraph(){}
void IMPL addEdge(){}
void IMPL removeEdge(){}
此外,您甚至都不应该想要这样做。重点是什么。除了它是C ++规则之外,它还使您知道您实际上正在实现成员函数。
不,没有办法避免它。否则,您如何知道给定的函数定义是用于类函数还是静态函数?
如果询问是否可以在不指定类名限定的情况下定义诸如Graph::printGraph
之类的成员函数,则答案为否,而不是所需的方式。这在C ++中是不可能的:
实现文件:
void printEdge(){};
上面的代码可以很好地编译,但是不会执行您想要的操作。它不会在Graph
类中用相同的名称定义成员函数。相反,它将声明并定义一个名为printEdge
的新自由函数。
这是好事,如果您觉得有点麻烦,因为您可能想要两个具有相同名称但作用域不同的函数。考虑:
// Header File class A { void foo(); }; class B { void foo(); }; void foo(); // Implementation File void foo() { }
该定义应适用于哪个范围? C ++不会限制您在不同范围内使用具有相同名称的不同函数,因此您必须告诉编译器您要定义的函数。
//yes it is possible using preprocessor like this:
#define $ ClassName //in .cpp
void $::Method1()
{
}
//or like this: in the header .h:
#undef $
#define $ ClassName'
// but you have to include the class header in last #include in your .cpp:
#include "truc.h"
#include "bidule.h" ...
#include "classname.h"
void $::Method() { }
//i was using also
#define $$ BaseClass
//with single inheritance than i can do this:
void $::Method()
{
$$::Method(); //call base class method
}
//but with a typedef defined into class like this it's better to do this:
class Derived : Base
{
typedef Base $$;
}
一个选项是using
。如果您在cpp文件中拥有永不获取#include
d的方法定义,则using
是安全的(不会影响其他文件):
编辑: