【发布时间】:2013-05-24 02:11:22
【问题描述】:
我正在开发一系列事件类。这些类包含从系统获取的信息。它们来自不同的性质,可能包含不同的消息,例如:一个可能的事件将包含一个巨大的数字列表,而另一个将携带字符串形式的查询信息。我想创建一个构建器函数来创建正确类型的事件并返回给用户。
下面是它的外观演示:
main.cpp:
#include <iostream>
#include "A.h"
#include "dA.h"
using namespace std;
int main()
{
cout << "Hello world!" << endl;
A a = build(5);
return 0;
}
事件.h:
#ifndef A_H_INCLUDED
#define A_H_INCLUDED
#include <iostream>
class A
{
public:
friend A build(int x);
protected:
A(int x);
private:
};
#endif // A_H_INCLUDED
event.cpp:
#include "A.h"
A::A(int x)
{
{
std::cout << "A\n";
std::cout << x << std::endl;
}
}
A build(int x)
{
if(x == 5)
return dA(x);
return make(x);
}
特殊事件.h
#ifndef DA_H_INCLUDED
#define DA_H_INCLUDED
#include <iostream>
#include "A.h"
class dA : public A
{
public:
protected:
dA(int x);
};
#endif // DA_H_INCLUDED
特殊事件.cpp:
#include "dA.h"
dA::dA(int x) : A(x)
{
std::cout << "dA\n";
}
如您所见,所有构造函数都受到保护,其目的是对用户隐藏构造——(s)他不应该从无到有创建事件,只有系统可以——并保证构建函数将返回正确的事件类型。
编译时,我得到:
error: 'build' was not declared in this scope
warning: unused variable 'a' [-Wunused-variable]
如果我把所有东西放在同一个文件中,我可以编译,但是,我最终会得到一个难以管理的大文件。注意上面的代码只是一个例子,我要使用的真实类是巨大的,放在同一个文件中,无论是声明还是实现,一切都变得一团糟。
【问题讨论】:
-
从 Joachim 的回答中遇到的错误来看,我的建议是将它们全部放入一个文件中。这样一来,如果您没有正确构建,或者实际上存在编码错误,您就可以隔离。
标签: c++ inheritance c++11 friend