这是一个大学项目的练习,目前正在学习面向对象编程,我对此比较陌生。
我有一个 Publication
类,它具有 Headline
和 Text
属性。
这是类的代码(头文件)
#include <iostream>
#include <string>
using namespace std;
using std::string;
class publication
{
private:
string headline,text;
public:
publication(); //constructor
void set_headline(string const new_headline);
void set_text(string const new_text);
string get_headline();
string get_text();
void print();
}
这是实现(.cpp 文件)
#include <iostream>
#include <string>
#include "publication.h"
using namespace std;
using std::string;
publication::publication()
{
publication.headline="";
publication.text="";
}
void publication::set_headline(string const new_headline)
{
publication.headline=new_headline; //any input is valid
}
void publication::set_text(string const new_text)
{
publication.text=new_text; //any input is valid
}
string publication::get_headline()
{
return publication.headline;
}
string publication::get_text()
{
return publication.text;
}
到目前为止我没有看到任何问题,如果我错了请纠正我。
这是我的问题:
我需要定义一个名为 Article
的新类。 Article
是 Publication
的一种类型,因此它继承自它,但它也有一个属于自己的独特字段,称为 Author
。
这是Article
类(头文件)的代码
#include <iostream>
#include <string>
#include "publication.h"
using namespace std;
using std::string;
class article: public publication
{
private:
string author;
public:
article();
void set_author(string const new_author);
string get_author();
}
这是实现(.cpp 文件)
#include <iostream>
#include <string>
#include "article.h"
using namespace std;
using std::string;
article::article()
{
article.author="";
article.set_headline("");
article.set_text("");
}
void article::set_author(string const new_author)
{
article.author=new_author;
}
string article::get_author()
{
return article.author;
}
这是我的问题:
在 set_author
方法中,我想检查输入是否有效。据我所知,没有叫 123
的人,也没有叫 Bob%^!@
的人。有没有办法检查字符串是否包含非字母字符?
最佳答案
首先让我指出几个我发现的问题。
在您的类构造函数和 setter 中,您不使用点分隔符为成员数据分配新值。
你在哪里publication.headline="";
, 你可以做 headline = "";
.这适用于您在自己的类中使用成员数据的所有情况,因此它适用于您的 article
类也是。
其次,在你的article
类(class)。您为继承设置 .h 文件的方式是正确的;但是,在构造函数的 .cpp 中,您必须扩展 publication
构造函数到 article
像这样的构造函数...
article::article() : publication()
{
....
}
: publication()
是对 super
的调用类的构造函数,没有它,headline
和 text
数据成员不会被初始化。
这也是 const
的常见做法以这种风格编写的变量:const <data-type> <variable-name>
,所以你有string const new_author
或任何类似的东西,只需切换到 const string new_author
.
现在,至于按照您所说的方式验证您的输入,您可以使用我想到的两种不同方法。一种是使用 isalpha()
方法,另一个是使用 ASCII
表来检查每个字符的值。
ASCII方法...通过每个字符的简单迭代器并检查值是否介于 65 和 90 或 97 和 122 之间...(请参阅 ascii 表以获得帮助)。对于这个例子,我将使用一个名为 name
的变量对于输入字符串变量。
for (int i = 0; i < strlen(name); i++)
{
if ((int(name[i]) >= 65 && int(name[i]) <= 90)
|| (int(name[i]) >= 97 && int(name[i]) <= 122))
{
...the character is A-Z or a-z...
}
}
函数方法...
for (int i = 0; i < strlen(name); i++)
{
if (!(isalpha(name[i])))
{
...the character is only A-Z or a-z...
}
}
希望对您有所帮助!编程愉快!
关于c++ - 检查输入的有效性 - Setter 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32323519/