用第一个构造函数执行第二个构造函数
Execute second constructor with first constructor
我有一个 class,它将根据内容和使用的方法解析 XML 文件和 return 数据。我希望能够使用带路径的文件名或指向已打开文件的指针来启动对象。
如果给出了指向已打开文件的指针,那么它将运行构造函数,仅此而已。如果传递了文件名,那么该构造函数将打开文件,然后将打开的文件的地址传递给第二个构造函数。
//foo.h
class foo
{
public:
foo(const QString fileName);
foo(QFile *fp);
...
...
}
//foo.cpp
class foo::foo(const QString fileName)
{
if(fileName.isEmpty()) {
// Return error.
} else {
// Open file and pass the address to the second constructor.
fp = new QFile(fileName);
fp->open(...);
foo::foo(fp); // Execute second constructor.
}
}
class foo::foo(QFile *fp)
{
if(fp == NULL) {
// Return error.
} else {
// Do stuff with open file and further initiate the object.
}
}
这是我关于如何执行此操作的第一个想法,但我觉得我把问题复杂化了。这是一种可行的方法吗?它是否明智?是否有针对此类情况的最佳实践?
在 C++11
中,您有 delegating constructors 可以提供帮助。
如果 C++11
不是一个选项,请重构您的代码以拥有一个私有 "initialize" 函数来完成繁重的工作并从每个构造函数中调用它。
class foo
{
public:
foo(const QString fileName) { /* open QFile, call load() */ }
foo(QFile *fp) { load(fp); }
...
private:
void load(QFile* fp);
};
我有一个 class,它将根据内容和使用的方法解析 XML 文件和 return 数据。我希望能够使用带路径的文件名或指向已打开文件的指针来启动对象。
如果给出了指向已打开文件的指针,那么它将运行构造函数,仅此而已。如果传递了文件名,那么该构造函数将打开文件,然后将打开的文件的地址传递给第二个构造函数。
//foo.h
class foo
{
public:
foo(const QString fileName);
foo(QFile *fp);
...
...
}
//foo.cpp
class foo::foo(const QString fileName)
{
if(fileName.isEmpty()) {
// Return error.
} else {
// Open file and pass the address to the second constructor.
fp = new QFile(fileName);
fp->open(...);
foo::foo(fp); // Execute second constructor.
}
}
class foo::foo(QFile *fp)
{
if(fp == NULL) {
// Return error.
} else {
// Do stuff with open file and further initiate the object.
}
}
这是我关于如何执行此操作的第一个想法,但我觉得我把问题复杂化了。这是一种可行的方法吗?它是否明智?是否有针对此类情况的最佳实践?
在 C++11
中,您有 delegating constructors 可以提供帮助。
如果 C++11
不是一个选项,请重构您的代码以拥有一个私有 "initialize" 函数来完成繁重的工作并从每个构造函数中调用它。
class foo
{
public:
foo(const QString fileName) { /* open QFile, call load() */ }
foo(QFile *fp) { load(fp); }
...
private:
void load(QFile* fp);
};