gpt4 book ai didi

c++ - 创建具有多态性和 op 的模板。 C++中的重载

转载 作者:行者123 更新时间:2023-11-28 05:40:21 25 4
gpt4 key购买 nike

我是学C++的,想请教:

如何在模板中转换类“时间”?像这样的东西:

template <class genericType>
class time {

我不擅长 C++,我想做的是在 main 中使用其他类型的数据,而不仅仅是下面代码中的“int”。

我想做这样的事情:

time <char>t('a','a','a');
t.show();

er <char>t2('b','b','b');
t2.show();

time <char>t3=t+t2;
t3.show();

谢谢大家。这是我想在模板中转换的代码:

#include <iostream>
using namespace std;

class time{
protected:

int hour, minuts , seconds;

public:

time(int x=0, int y=0, int z=0){
hour=x;
minuts=y;
seconds=z;
}
virtual void show(){
cout<<"it's "<<hour<<":"<<minuts<<":"<<seconds<<endl;
}


time operator+(time &te){

cout<<"sum everything: ";
time bho;
bho.hour=hour+te.hour;
bho.minuts+=minuts+te.minuts;
bho.seconds+=seconds+te.seconds;
return bho;
}

};

class er: public time {

public:

er(int x=0,int y=0,int z=0):time(x,y,z){};

void show() {
cout<< "Inside er: it's "<<hour<<":"<<minuts<<":"<<seconds<<endl;
};
};

int main()
{

time t(10,10,10);
t.show();

er t2(20,20,20);
t2.show();

time *pt= new er(60,60,60);
pt->show();

time t3=t+t2;
t3.show();

return 0;
}

最佳答案

这是真的,@serge Ballesta 的解决方案是错误的。也许你可以试试这个:

#include <iostream>
using namespace std;

template <class genericType>
class time{
protected:

genericType hour, minutes , seconds;

public:

time(genericType x=0, genericType y=0, genericType z=0){
hour=x;
minutes=y;
seconds=z;
}
virtual void show(){
cout<<"it's: "<<hour<<":"<<minutes<<":"<<seconds<<endl;
}

time operator+(time &te){

cout<<"sum everything: "<<endl;
time bho;
bho.hour=hour+te.hour;
bho.minutes+=minutes+te.minutes;
bho.seconds+=seconds+te.seconds;
return bho;
}

};

template <class genericType>
class er: public time <genericType>{

public:

er(genericType x=0,genericType y=0, genericType z=0){
time<genericType>::hour=x;
time<genericType>::minutes=y;
time<genericType>::seconds=z;
}

void show() {
cout<< "Inside er: it's "<<time<genericType>::hour<<":"<<time<genericType>::minutes<<":"<<time<genericType>::seconds<<endl;
};
};

int main()
{
time <char>t('a','a','a');
t.show();

er <char>t2('b','b','b');
t2.show();

time <char>t3=t+t2;
t3.show();

return 0;
}

关于c++ - 创建具有多态性和 op 的模板。 C++中的重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37243944/

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