есть такой код:
h:
class TReditor : public TableEditor
{
public:
TReditor(QWidget *parent = 0);
};
TReditor::TReditor(QWidget *parent) : TableEditor(MY_CONST, parent)
{
...
}
class TReditor : public TableEditor
{
public:
TReditor(const QString &tr_type, QWidget *parent = 0);
};
#define ?
в зависимости от переменной!
#define на этапе компиляции только.
У меня родительский конструктор объявлен так:
TableEditor(int type, QWidget *parent = 0), а дочернему передается строковая переменная.
т.е. есть такая часть строки:
: TableEditor(MY_CONST, parent)
как ее засунуть в тело конструктора, чтоб получилось примерно такое:
switch (tr_type)
{
case STR_CONST_1: :TableEditor(INT_CONST_1, parent);
case STR_CONST_2: :TableEditor(INT_CONST_2, parent);
case STR_CONST_3: :TableEditor(INT_CONST_3, parent);
}
MyClass::MyClass(Type *var) : MyParentClass(var)
{
}
Как вариант можно использовать шаблон:
template<const int nConst>
class TReditor : public TableEditor
{
public:
TReditor(QWidget *parent = 0);
};
template<const int nConst>
TReditor<nConst>::TReditor(QWidget *parent) : TableEditor(nConst, parent)
{
//...
}
Выбирай сам...
Мне кажется ты слишком заморачиваешься. Просто вынеси инициализацию из конструктора в метод TableEditor::Init(int type), вызывай его потом с нужным параметром...
Если не слишком много возможных вариаций - то можно через тернарный оператор
TReditor::TReditor(const QString &tr_type, QWidget *parent) :
TableEditor(tr_type == "MyType" ? MY_TYPE : CONST_TYPE, parent);
а сам switch туда нельзя засунуть?
#define SWITCH_MACROS(tr_type) /
switch (tr_type) /
{ /
case STR_CONST_1: :TableEditor(INT_CONST_1, parent); /
case STR_CONST_2: :TableEditor(INT_CONST_2, parent); /
case STR_CONST_3: :TableEditor(INT_CONST_3, parent); /
}
TReditor::TReditor(const QString &tr_type, QWidget *parent) : TableEditor( SWITCH_MACROS( tr_type), parent){}
ViGOur, это не будет компилироватся
Litkevich Yuriy
#include <iostream>
#include <string>
int ConstructorInit(const std::string & sStr)
{
if (sStr == "1")
return 1;
if (sStr == "2")
return 2;
return -1;
}
class Foo
{
public:
Foo(int nParam)
{
std::cout<<nParam<<std::endl;
}
};
class Bar : public Foo
{
public:
Bar(std::string & sParam) : Foo(ConstructorInit(sParam))
{}
};
int main()
{
Bar(std::string("1")); // 1
Bar(std::string("14")); // -1
Bar(std::string("2")); // 2
return 0;
}
Форум Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)