1、在这个类定义中找出编程错误。给出两种不同的修正方法。类定义如下:class Glove { public: Glove (int cFingers) : _n (cFingers), _hand (_n) { cout << “Glove with ” << _n << ” fingers\n”; } private: Hand _hand; int _n; }; 假设 Hand 类已经定义,其构造函数接受一个整数参数。
错误分析
在这个类定义中,成员变量的初始化顺序是按照它们在类中声明的顺序进行的,而不是按照构造函数初始化列表中的顺序。在这个类中, _hand 先于 _n 声明,所以 _hand 会先被初始化。然而,在初始化列表中, _hand 使用了 _n 来初始化,此时 _n 还未被初始化,这会导致未定义行为。
修正方法
方法一:调整成员变量的声明顺序
将 _n 的声明放在 _hand 之前,这样 _n 会先被初始化, _hand 就可以使用已初始化的 _n 来进行初始化。
#include <iostream>
// 假设 Hand 类已经定义
class Hand {
public:
Hand(int fingers) {}
};
class Glove {
public:
Glove(int cFingers) : _n(cFingers), _hand(_n) {
std::cout << "Glove with " << _n << " fingers\n";
}
private:
int _n;
Hand _hand;
};
方法二:在构造函数体内初始化 _hand
不在初始化列表中初始化 _hand ,而是在构造函数体内进行初始化,这样可以确保 _n 已经被初始化。
#include <iostream>
// 假设 Hand 类已经定义
class Hand {
public:
Hand(int fingers) {}
};
class Glove {
public:
Glove(int cFingers) : _n(cFingers) {
_hand = Hand(_n);
std::cout << "Glove with " << _n << " fingers\n";
}
private:
Hand _hand;
int _n;
};
2、定义一个名为HorBar的类,该类的构造函数打印如下模式 +----------+ ,其中减号的数量作为一个整数参数传递给构造函数。
#include <iostream>
class HorBar {
public:
HorBar(int n) {
std::cout << "+";
for (int i = 0; i < n; ++i) {
std::cout << "-";
}
std::cout << "+" << std::endl;
}
};
3、修改栈,使其成为 CharStack(字符栈)。通过将字符串的所有字符压入栈中,然后逐个弹出并打印这些字符,用它来反转字符串。
以下是实现将栈修改为字符栈并用于反转字符串的代码:
// stack.h
const int maxStack = 16;
class CharStack {
public:
CharStack() : _top(0) {}
void Push(char c);
char Pop();
private:
char _arr[maxStack];
int _top;
};
// stack.cpp
#include "stack.h"
#include <cassert>
void CharStack::Push(char c) {
assert(_top < maxStack);
_arr[_top++] = c;
}
char CharStack::Pop() {
assert(_top > 0);
return _arr[--_top];
}
// main.cpp
#include "stack.h"
#include <iostream>
#include <cstring>
int main() {
CharStack stack;
const char* str = "hello";
int len = strlen(str);
// 将字符串的字符压入栈中
for (int i = 0; i < len; ++i) {
stack.Push(str[i]);
}
// 从栈中弹出字符
C++编程错误与字符串操作解析

最低0.47元/天 解锁文章
8787

被折叠的 条评论
为什么被折叠?



