gpt4 book ai didi

C++ 字符串继承

转载 作者:太空狗 更新时间:2023-10-29 21:02:10 24 4
gpt4 key购买 nike

所以我在 Inheritance 上发现了这个问题,我想弄清楚。这是必需的:

Create a class called strMetric that will give information about a string. You should provide a default constructor and an overloaded constructor that takes a string as an argument.

Your string metric class should have the following functioality

A method called howLong that returns the length of the string

A method called vowelCnt that returns the number of vowels in a string

A method called charSum that returns the sum of all characters within the string

A method called upperCase that returns the number of upper case characters

A method called lowerCase that returns the number of lower case characters

You are to use the strMetric class as the derived class and use the string class as the base class.

NOTE:

Do not not create your own string class and derive from it. You are to use the string class that is part of the std namespace and defined in

我一直在解决这个问题,这就是我所拥有的,(现在我只研究其中一种方法,直到我弄清楚如何正确地做到这一点)

////strmetric.h////

#ifndef STRMETRIC
#define STRMETRIC
#include <string>
using namespace std;

class strMetric : public string
{
private:

public:
strMetric();
strMetric(string &s);
int howLong(string s);
};
#endif

////strmetric.cpp////

#include "strmetric.h"

strMetric::strMetric()
:string()
{
}
strMetric::strMetric(string &s)
:string(s)
{
}

int strMetric::howLong(string s)
{
return s.size();
}

/////main.cpp////

#include <iostream>
#include "strmetric.h"

strMetric testRun("Hello There");

int main()
{

cout << "Here is the sentence being tested " << endl;
cout << endl;
cout << testRun << endl;
cout << endl;
cout << "String length " << endl;
cout << endl;
cout << testRun.length(testRun) << endl;
cout << endl;

}

那么我这样做是正确的,还是偏离了基本点?我很难理解这个问题。如果我做错了,有人可以告诉我如何正确做,我不需要整个事情,只需要我开始的一部分,这样我就可以很好地了解我应该做什么,谢谢!

最佳答案

抛开一个普遍的好建议不要继承std容器,而更喜欢组合,你仍然没有做对: howLong 方法(以及他们希望您定义的其他方法)应该对字符串本身进行操作,而不是对传入的字符串进行操作:

int howLong(); // no args

int strMetric::howLong() {
// Using "this" below is optional
return this->size(); // remember, this *is* a string
}

其余方法将做同样的事情 - 它们将采用字符串参数,而是使用this

How in the world can you do the other methods using this-> instead of loading in a string argument?

其余的方法没有什么不同 - 只需将字符串放入您自己的对象中即可。我几乎可以肯定,学习如何做到这一点是练习的重点。例如,要添加元音计数器,您可以这样做:

int vowelCnt(); // again, no args

int strMetric:: vowelCnt() {
int res = 0;
for (int i = 0 ; i != this->size() ; i++) {
char ch = (*this)[i]; // Yes, this works
if (ch == 'a' || ch == 'u' || ch == ...) {
res++;
}
}
return res;
}

关于C++ 字符串继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16094993/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com