有做适当的问题 [英] Having problem to do appropriately

查看:54
本文介绍了有做适当的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题
创建一个AlphaString类,该类仅将字母存储在任意长度的字符串中.该字符串具有一个构造函数,可确保该字符串仅包含字母.该类还具有一个复制构造函数和一个重载的+运算符.重载的+运算符应执行两个字符串的串联.

Question
Create a class AlphaString that stores only alphabets in a string of arbitrary length. The string has a constructor that makes sure that String has only Alphabets. The class also has a copy constructor, and an overloaded + operator. The overloaded + operator should perform the concatenation of two strings.

#include <string.h>
#include<iostream.h>
#include<conio.h>
using namespace std;

class AlphaString {
public:
   AlphaString( char *ch );  // Declare constructor
   ~AlphaString();           //  and destructor.
private:
   char    *_text;
   size_t  sizeOfText;
};

AlphaString::AlphaString( char *ch ) {
    int i=1;
    int k=int(ch[i]);
    int flag=0;
    while(strlen(ch))
    {
        if((k>=65 && k<=90) || (k>=97 && k<=122))
           flag =0;
        else
        {
           flag =1;
           break;
        }
        k=int(ch[i]);
        i++; 
    }
    sizeOfText = strlen( ch ) + 1;
    if(flag==0)
    {
        // Dynamically allocate the correct amount of memory.
        _text = new char[ sizeOfText ];
    }
}

// Define the destructor.
AlphaString::~AlphaString() {
   // Deallocate the memory that was previously reserved
   //  for this string.
   if (_text)
        delete[] _text;
   }
   
// Copy Constructor.
AlphaString::AlphaString(AlphaString & objB) {
}
int main() {
    char str[25];
    cout<<"Enter First String: ";
    cin>>str;
    AlphaString ob1(str);
    cout<<"Enter Second String: ";
    cin>>str;
    AlphaString ob2(str);
    cout<<ob1._text+ob2._text;
    AlphaString ob3(ob1);
    
    getch();
    return 0;
}



[edit]添加了代码块以保留格式-OriginalGriff [/edit]
[edit]正确的代码对齐和大括号-Andrew Brock [/edit]



[edit]Code block added to preserve formatting - OriginalGriff[/edit]
[edit]Corrected code alignment and balanced braces - Andrew Brock[/edit]

推荐答案

AlphaString::AlphaString( char *ch ) { //You are not changing the contents of ch, so why not make it const?
    int i=1; //All array indices start at 0 in C++. Strings included.
    int k=int(ch[i]); //This is the 2nd character in the string
    int flag=0; //You should use meaningful variable names, like onlyAlpha
    //while(strlen(ch)) is just horrid.
    //The length of the string never changes, so you might as well have while(1)
    //Furthermore, strlen works by iterating over every character in the string to find the termination character. This is happening every loop.
    while(strlen(ch))
    {
        if((k>=65 && k<=90) || (k>=97 && k<=122)) //Why not use characters (as Richard MacCutchan suggested)
           flag =0; //flag is already 0. Why are you setting it again?
        else
        {
           flag =1;
           break;
        }
        k=int(ch[i]); 
        i++;
    }
    sizeOfText = strlen( ch ) + 1;
    if(flag==0)
    {
        // Dynamically allocate the correct amount of memory.
        _text = new char[ sizeOfText ];
        //What are the contents of _text? It is not the string.
    }
    //What happens to _text if flag != 0?
    //It remains uninitialised, and likely does not hold the value NULL.
    //This will cause problems with the destructor.



更正的解决方案:



A corrected solution:

AlphaString::AlphaString(const char *ch) : _text(0), sizeOfText(0) {
    int i = 0;
    bool bOnlyAlpha = true; //You should use meaningful variable names, like onlyAlpha
    while(ch[i] != 0) { //0 is the null terminator
        if((ch[i]<''A'' || ch[i]>''Z'') && (ch[i]<''a'' || ch[i]>''z''))
           flag =0; //flag is already 0. Why are you setting it again?
           bOnlyAlpha = false;
           break;
        }
        ++i;
    }
    sizeOfText = i + 1; //If you are paying attention, you will notice that i holds the length of the string, not including the terminator
    if (bOnlyAlpha) {
        // Dynamically allocate the correct amount of memory.
        _text = new char[sizeOfText];
        memcpy(_text, ch, sizeOfText); //Could use strcpy, but memcpy is faster
    }
}


我想你想要这样的东西:
I think you want something like this:
#include<ctype.h>

class AlphaString 
{
public:   
	AlphaString( char *ch );  
	// Declare constructor   
	~AlphaString();           
	//  and destructor.
private:   
	char    *_text;   
	size_t  sizeOfText;
};
AlphaString::AlphaString( char *ch ) 
	: _text(0),sizeOfText(0) 
// Initialize to make sure they don''t contain garbage, 
// as required by your destructor
{    
	if(ch)
	{
		size_t numberOfCharacters = 0;
		char* ptr = ch;
		while(*ptr) // figure out the required memory size 
		{
			char c = *ptr;
			if(isalpha(c))
			{
				numberOfCharacters++;
			}
			ptr++;
		}
		if(numberOfCharacters)
		{
			_text = new char[numberOfCharacters+1];
			
			char* ptrSource = ch;
			char* ptrDestination = _text;
			while(*ptrSource) // copy the alphbetic characters
			{
				char c = *ptrSource;
				if(isalpha(c))
				{
					*ptrDestination = c;
					ptrDestination++;
				}
				ptrSource++;
			}
			_text[numberOfCharacters] = ''\x0''; // zero terminate the string
			sizeOfText = numberOfCharacters;
		}
	}
}



这应该工作:)-您可以使用自己的析构函数实现...

该构造函数解决了一些重要问题:
1.成员变量的初始化:
_text(0),sizeOfText(0)
C ++不会初始化成员变量,这是您必须自己执行的事情.

2. if(ch)测试ch是否不为NULL –如果是,则原始代码有问题

3.计算字母字符的数量

4.如果有任何字母字符-分配所需的内存量:
字母字符数+ 1(用于终止零)

5.仅将字母字符 复制到分配的缓冲区

6.零终止缓冲区


问候
Espen Harlinn



This should work :) - you can use your own destructor implementation ...

This constructor addresses a few important points:
1. Initialization of member variables:
_text(0),sizeOfText(0)
C++ does not initialize member variables, that’s something you have to perform yourself.

2. if(ch) tests if ch is not NULL – if it is, the original code is in trouble

3. count the number of alphabetic characters

4. if there are any alphabetic characters - allocate the required amount of memory:
number of alphabetic characters + 1 (for terminating zero)

5. copies only the alphabetic characters to the allocated buffer

6. zero terminates the buffer


Regards
Espen Harlinn


if((k>=65 && k<=90) || (k>=97 && k<=122))


为什么不通过以下代码来使其可读:


Why not make it readable by coding like:

if((k >= ''A'' && k <= ''Z'') || (k >= ''a'' && k <= ''z''))


这篇关于有做适当的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆