【发布时间】:2010-05-07 21:45:54
【问题描述】:
我刚参加了一次考试,被问到以下问题:
为下面给定的代码编写 GenStrLen、InsertChar 和 StrReverse 方法的函数体。您必须考虑以下事项;
- 如何在 C++ 中构造字符串
- 字符串不能溢出
- 插入字符会将其长度增加 1
- StrLen = 0 表示空字符串
class Strings {
private:
char str[80];
int StrLen;
public:
// Constructor
Strings() {
StrLen=0;
};
// A function for returning the length of the string 'str'
int GetStrLen(void) {
};
// A function to inser a character 'ch' at the end of the string 'str'
void InsertChar(char ch) {
};
// A function to reverse the content of the string 'str'
void StrReverse(void) {
};
};
我给出的答案是这样的(见下文)。我的一个问题是使用了许多额外的变量,这让我相信我没有以最好的方式做到这一点,另一件事是这不起作用....
class Strings {
private:
char str[80];
int StrLen;
int index; // *** Had to add this ***
public:
Strings(){
StrLen=0;
}
int GetStrLen(void){
for (int i=0 ; str[i]!='\0' ; i++)
index++;
return index; // *** Here am getting a weird value, something like 1829584505306 ***
}
void InsertChar(char ch){
str[index] = ch; // *** Not sure if this is correct cuz I was not given int index ***
}
void StrRevrse(void){
GetStrLen();
char revStr[index+1];
for (int i=0 ; str[i]!='\0' ; i++){
for (int r=index ; r>0 ; r--)
revStr[r] = str[i];
}
}
};
如果有人能大致解释一下回答问题的最佳方式和原因,我将不胜感激。还有我的教授怎么会像“};”这样关闭每个类函数,我认为这仅用于结束类和构造函数。
非常感谢您的帮助。
【问题讨论】:
-
函数后只需要
},尽管};在语法上是有效的。;在这种情况下完全没有任何作用 -
啊,好的,谢谢,因为这也让我有些困惑
-
我很想把这个归档在作业标签下,但这不是作业。我们需要一个考试标签。
-
根据你教授的代码,他显然是一个光荣的C程序员,碰巧知道如何创建类,并认为他知道C++。例如,在 C++ 中允许使用 void 参数,但不是惯用的 C++ 或良好的 C++ 风格。此外,他应该将 GetStrLen() 声明为“const”,但没有这样做。我建议您阅读 Neil Gray 的“A Beginnner's C++”、“Learn C++ in 21 Days”和“Parashift C++ FAQ Lite”。它们是熟悉 C++ 的极好资源,而且它们可能会比您的教授做得更好。
-
[继续] 这并不是说您的解决方案是正确的;你的代码有很多问题....但是考虑到我在教授的代码中看到的问题,我认为我提到的资源会更好地向你解释基本概念。