Ter*_*ght -2 c++ templates boolean class
//我使用的是布尔函数,它返回一个false和true,但主要不是//拾取它。假设my_string.Is_full和my_string.Is_empty说“它不//满”和“它不为空”。语法错误?
#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;
}
}
Run Code Online (Sandbox Code Playgroud)
// 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;
}
}
Run Code Online (Sandbox Code Playgroud)
// 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;
}
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
my_String.Is_Full();
if (true)
{
cout << "It is full" << endl;
}
Run Code Online (Sandbox Code Playgroud)
这是不正确的:您调用Is_Full(),它返回false,但是不使用返回值。然后,您检查true是否为true,并且显然是。
您应该改为:
if (my_String.Is_Full())
{
cout << "It is full" << endl;
}
else
{
...
}
Run Code Online (Sandbox Code Playgroud)
关于编译器警告,在某些情况下,函数根本不返回,您应该用简单的else替换“ else if”,或者在条件范围之外添加return语句。