【发布时间】:2014-09-22 10:29:20
【问题描述】:
// 我正在使用一个布尔函数,它返回一个 false 和 true,但主要不是 //picking 它。 my_string.Is_full 和 my_string.Is_empty 应该说“它不是 //full”和“它不是空的。语法错误?
#include <iostream>
#include <string>
using namespace std;
const int SIZE = 5;
template <class New_Type>
class Array_Class
{
public:
Array_Class();
~Array_Class();
void Add(New_Type item);
void Print();
void PrintB();
bool Is_Empty();
bool Is_Full();
private:
New_Type *A;
New_Type *B;
int count;
};
template <class New_Type>
Array_Class<New_Type>::Array_Class()
{
cout << "You are inside the default constructor.\n";
cout << "New_Type has a size of " << sizeof(New_Type) << " bytes\n\n";
count = 0;
A = new New_Type[SIZE];
}
template <class New_Type>
Array_Class<New_Type>::~Array_Class()
{
cout << "The Destructor has been called.\n\n";
delete[] A;
count = 0;
A = 0;
}
template <class New_Type>
void Array_Class<New_Type>::Add(New_Type item)
{
if (count<SIZE)
{
A[count++] = item;
}
else
{
cout << "The array is full.\n";
}
}
template <class New_Type>
void Array_Class<New_Type>::Print()
{
int i;
for (i = 0; i<count; i++)
{
cout << "A[" << i << "] = " << A[i] << endl;
}
}
//my_String 到这里,结果是 False
template <class New_Type>
bool Array_Class<New_Type>::Is_Full()
{
if (count == SIZE)
{
return true;
}
else if (count < SIZE)
{
return false;
}
}
//my_String 到这里,结果是 False
template <class New_Type>
bool Array_Class<New_Type>::Is_Empty()
{
if (count == 0)
{
return true;
}
else if (count > 0)
{
return false;
}
}
int main()
{
Array_Class<string> my_String;
Array_Class<int> my_Ints;
Array_Class<char> my_Chars;
my_String.Add("Hello");
my_String.Add("GoodBye");
my_String.Add("ComeHere");
my_String.Add("SayNo");
my_Chars.Add('a');
my_Chars.Add('b');
my_Chars.Add('c');
my_Chars.Add('d');
my_Chars.Add('e');
my_Chars.Add('f');
my_Chars.Add('g');
my_String.Print();
my_Ints.Print();
my_Chars.Print();
cout << endl;
my_Ints.Is_Empty();
if (true)
{
cout << "It is empty" << endl;
}
else
{
cout << "It is not empty\n" << endl;
}
my_String.Is_Empty();应该是假的,但直接变成真
my_String.Is_Empty();
if (true)
{
cout << "It is empty" << endl;
}
else
{
cout << "It is not empty\n" << endl;
}
cout << endl;
my_Chars.Is_Full();
if (true)
{
cout << "It is full" << endl;
}
else if (false)
{
cout << "It is not full" << endl;
}
my_String.Is_Full();应该是假的,但直接变成真
my_String.Is_Full();
if (true)
{
cout << "It is full" << endl;
}
else if (false)
{
cout << "It is not full" << endl;
}
return 0;
}
【问题讨论】:
-
当
count < 0时你期望它返回什么? -
因为 count 永远不能小于 0,所以您可以正确地忽略它,但是您对 if 语句的措辞方式很尴尬,并且编译器会正确地抱怨如果
count是 小于0,则此代码会导致问题。而是将整个函数更改为return count == 0;forisEmpty和return count == SIZE;forisFull -
如果 size 是编译时常量,为什么要动态分配数组?
-
数组的元素个数永远不能少于 0,这是一个事实。所以我会将计数声明为无符号整数。简单直接。
-
没有计数
标签: c++ class templates boolean