提问人:Uwe_98 提问时间:6/3/2013 最后编辑:SpookUwe_98 更新时间:6/4/2013 访问量:115
C++。1参数变化的类
C++. 1Class with changing parameters
问:
我有一个包含 3 个私有变量和一个公共方法的类,其中包含 2 个 char 参数变量。
class InitLine
{
private:
char *a;
char b, c;
public:
InitLine(char *inita, char initc);
Init(char *a, char c);
};
现在该方法的定义很简单:
Initline::Init(char *a, char c)
{
for (b=0; b<c; b++)
*(a+c)=0;
}
现在我的问题是:如果我希望使用不同的参数类型(*a 和 c,或者其中一个变成整数,例如),是否有必要创建一个新类,或者我可以使用现有的类,做一些“类型转换”或其他一些我还不知道的技巧?
谢谢和问候
乌韦
答:
1赞
dzada
6/3/2013
#1
使用模板,使 Init 函数成为参数类型的模板。
template <typename T>
Init(char*a , T c){}
例如
0赞
Nicholaz
6/3/2013
#2
如果你只想让整个类具有不同的类型(不仅仅是 Init),例如还有 int *a;int b,c;那么模板类是你还不知道的另一个技巧。
template <typename ANYTYPE> class InitLine
{
private:
ANYTYPE *a;
ANYTYPE b, c;
public:
void InitLine(ANYTYPE *inita, ANYTYPE initc);
void Init(ANYTYPE *a, ANYTYPE c);
};
template <typename ANYTYPE> void Initline<ANYTYPE>::Init(ANYTYPE *a, ANYTYPE c)
{
for (int b=0; b<c; b++)
*(a+c)=0;
}
... main()
{
Initline<int> iline; // initline class based on type int (ANYTYPE -> int)
int line[20];
Initline<char> cline; // initline class based on type char (ANYTYPE -> char)
char somechars[30];
iline.Init(line, 20);
cline.Init(somechars, 30);
评论
0赞
Nicholaz
6/3/2013
向 main() 添加了更多代码,以显示如何基于模板制作一个 char 类型和一个 int 类型。
0赞
Uwe_98
6/4/2013
你好 Nicholaz,我想你提到了 'char somechars[30]。今天我尝试了这种方法。它不是这样工作的,但我的编译器只是接受它,如果你写:template <typename ANYTYPE> ANYTYPE Initline <ANYTYPE>::Init(ANYTYPE *a, ANYTYPE c)。坦克和问候
0赞
Nicholaz
6/4/2013
将编辑两者。哎呀......(如果这是帮助您解决问题的答案,请正确检查,将不胜感激)。
1赞
Spook
6/3/2013
#3
代码中有许多位置,在执行任何进一步操作之前应修复这些位置。
命名约定很糟糕。什么?
a
b
c
您用作循环索引器,而应在此处使用局部变量。
b
你不告诉我们,什么是.它分配在哪里?所指的内存大小是多少?
a
a
我想,您的代码应该如下所示:
class InitLine
{
private:
char * data;
int count;
public:
InitLine(char * newData, int newCount)
{
// Possible error checking?
data = newData;
count = newCount;
}
// No parameters needed here, I guess
void Init()
{
for (int i = 0; i < count; i++)
data[i] = 0;
}
};
至于你的问题,我不太确定,你想实现什么,你想知道什么。如果要编写包含任何类型数组的泛型类,则必须使用模板:
template <typename T>
class InitLine
{
private:
T * data;
int count;
public:
InitLine(T * newData, int newCount)
{
// Possible error checking?
data = newData;
count = newCount;
}
// No parameters needed here, I guess
void Init()
{
for (int i = 0; i < count; i++)
data[i] = 0;
}
};
您必须按以下方式使用此类:
InitLine<char> line(myData, myDataSize);
// where myData is a char * and myDataSize is an int
如果要编写一些参数不同的方法,则此技术称为方法重载,可在 C++ 中使用:
void Init(char * a, int b) { /* sth */ }
void Init(int * a, int b) { /* sth */ }
请注意,编译器必须能够清楚地区分应该调用哪个方法。例如。
void Test(int a) { }
void Test(char a) { }
Test(0); // Ambiguity: which method should be called?
这些只是在阅读您的问题时浮现在脑海中的事情。如果这不是您要求的,请考虑将问题编辑得更具体。
评论
0赞
Uwe_98
6/3/2013
所以我必须重复整个方法的衰减和定义?试着像其他人一样理解问题,而不是专注于我没有要求的不重要的细节。谢谢和问候Uwe
评论
a
b
c
b
InitLine::b