gpt4 book ai didi

c++ - 我怎样才能让 parent 实例化它的 child ?

转载 作者:行者123 更新时间:2023-11-28 08:14:09 24 4
gpt4 key购买 nike

我有一个父类测试,子类是子测试。当我调用 test->run() 时,我想运行我所有的子测试。下面的代码在公元前不起作用。子类在父类中不被识别。

using namespace std;
class test
{
protected:
short verbosity_;
public:
void setVerbosity(short v)
{
if((v==0 || v==1 || v==2))
{
verbosity_ = v;
}
else
{
cout << " Verbosity Level Invalid " << endl;
}
}
void run()
{
natives natives_1; // this does not work
}
};
class natives : public test
{
public:
natives()
{
this->run();
}
void run()
{
testInts<short>();
testInts<int>();
testInts<long>();
testInts<unsigned short>();
testInts<unsigned int>();
testInts<unsigned long>();
}
protected:
template<class T> void testFloats()
{
}
template<class T> void testInts()
{
short passState, bitDepth;
T failMax, pow2 = 1, minValue = 0, maxValue = 0, bitCount = 0, failValue = 0;
const char* a = typeid(T).name();
bool signedType = ((*a == 't') || (*a == 'j') || (*a == 'm'));
while(pow2 > 0)
{
pow2 *= 2;
bitCount++;
}
maxValue = pow2-1;
failValue = pow2;
int native1 = bitCount;
int native2 = sizeof(T)*8;
int native3 = numeric_limits<T>::digits;
if( !signedType )
{
native1++;
native3++;
}
if(verbosity_>=1) cout << endl << "**********\n" << reportType(a) << "\n**********" << endl << endl;
if ((native1 == native2) && (native1 == native3))
{
if(verbosity_>=1)cout << "Correlation:\t\tPass: " << native1 << endl ;
if(verbosity_>=2)
{
cout << "--Algorithm:\t\t" << native1 << endl;
cout << "--Sizeof:\t\t" << native2 << endl;
cout << "--Reported:\t\t" << native3 << endl;
cout << "----Max Value:\t\t" << maxValue << endl;
cout << "----Max+1\t\t" << failValue << endl;
}
else
{
}
}
else
{
cout << "Correlation:\t\tFail" << endl ;
}
}
string reportType(const char* c1)
{
string s1;
switch(*c1)
{
case 't':
s1 = "Unsigned short";
break;
case 'j':
s1 = "Unsigned int";
break;
case 'm':
s1 = "Unsigned long";
break;
case 's':
s1 = "Short";
break;
case 'i':
s1 = "Int";
break;
case 'l':
s1 = "Long";
break;
default:
s1 = "Switch failed";
}
return s1;
}
};

最佳答案

可能更好的方法是在 test 类中创建一个名为 run 的纯虚函数,然后子类的测试将实现它并且当您在子类的实例上调用 run 时,这些将运行。

例如:

class Test {
public:
virtual void run() = 0;

void setVerbosity(short v) {
if((v==0 || v==1 || v==2))
verbosity_ = v;
else
cout << " Verbosity Level Invalid " << endl;
}
};

class Natives : public Test {
public:
void run() {
// do all the tests....
}
};

然后你可以做

Natives n;
n.run();

当您通过 Test*(或 Test&)执行此操作时,它们仍会运行:

Test* t = new Natives;
t->run(); // runs Natives::run

您也可以在这里使用 CRTP,但我认为没有必要。

关于c++ - 我怎样才能让 parent 实例化它的 child ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8189444/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com