gpt4 book ai didi

c++ - 指针模板数组 C++?

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

大家好,在我的 C++ 程序中,我有四个类(A、B、C、D)

  • A是基类
  • B继承自A
  • C继承自A
  • D继承自B

都是模板类template<class Type>它们每个都有一个 print 方法,打印它的私有(private)成员和它继承的类的私有(private)成员。

所以 B 将打印 B 私有(private)成员和 A 私有(private)成员,C 将打印 C 私有(private)成员和 A 私有(private)成员,D 将打印其私有(private)成员和 B,A 私有(private)成员。

在主函数中,我想为类 A 创建一个指针数组,每个类的一个对象有 3 个位置,然后我想循环每个对象打印方法。

问题是当我将类更改为模板类时,我收到一条错误消息“我的类没有构造函数”;但是他们确实有。

这是我的代码,请帮助(注意我为您评论了错误发生的地方):

#include <iostream>
#include <string>
using namespace std;

template <class Type>
class A
{
public:
virtual void print()
{
cout<<"the base class (A) private (x) is : "<<x<<endl;
}

A(Type X = 0)
{
x = X;
}
void setX(Type X)
{
x = X;
}

Type getX() const
{
return x;
}

private:
Type x;
};


template <class Type>
class B:public A
{
public:
B(Type X = 0,Type Y = 0)
{
setX(X);
y = Y;
}
void setY(Type Y)
{
y = Y;
}

Type getY() const
{
return y;
}

void print()
{
A::print();

cout<<"private (y) in class (B) is : "<<getY()<<endl;
}

private:
Type y;
};

template <class Type>
class C:public A
{
public:
C(Type X = 0,Type Z = 0)
{
setX(X);
z = Z;
}
void setZ(Type Z)
{
z = Z;
}

Type getZ() const
{
return z;
}

void print()
{
A::print();

cout<<"private (z) in class (C) is : "<<getZ()<<endl<<endl;
}

private:
Type z;
};


template <class Type>
class D:public B
{
public:
D(Type X = 0,Type Y = 0,Type W = 0)
{
setX(X);
setY(Y);
w = W;
}
void setW(Type W)
{
w = W;
}

Type getW() const
{
return w;
}

void print()
{
B::print();

cout<<"private (w) in class (D) is : "<<getW()<<endl;
}

private:
Type w;
};


void main()
{
A<int>* arrayOfPointers[3];

arrayOfPointers[0] = new B(1,100);//error here
arrayOfPointers[1] = new C(2,200);//error here
arrayOfPointers[2] = new D(3,300,3000);//error here

for(int i = 0 ; i<3;i++)
{
cout<<typeid(*arrayOfPointers[i]).name()<<" Print method : \n"<<endl;
arrayOfPointers[i]->print();
cout<<"**********************\n"<<endl;
}

}

最佳答案

你忘记了两件事:

1) 您的继承需要为其继承的类指定模板参数。例如:

template <class Type>
class B : public A<Type>
{
...
}

2) 当你实例化你的类时,你也需要提供模板参数:

arrayOfPointers[0] = new B<int>(1, 100);
arrayOfPointers[1] = new C<int>(2, 200);
arrayOfPointers[2] = new D<int>(3, 300, 3000);

但是,您也可以提供模板函数以根据提供的参数实例化这些类,例如 std 库中的那些 make_(...) 方法:

template <class Type>
B<Type>* create_B(const Type& t1, const Type& t2)
{
return new B<Type>(t1, t2);
}

并像这样使用它:

 arrayOfPointers[0] = create_B(1, 100);

但是,请注意,这些方法正在创建指向已分配堆内存的原始指针,因此您有责任删除它(您可以使用 shared_ptr 或其他任何方法来克服它,或者只是返回一个对象等,但这实际上不是您的一部分问题/我的回答)。

关于c++ - 指针模板数组 C++?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38527670/

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