使用类,但无法显示答案。

Working with classes but can't display the answer.

本文关键字:显示 答案      更新时间:2023-10-16

我真的不想写这个问题,但我似乎无法输出名称。这是我班作业的一部分,也是作业中最难的部分,但我的老师说,只要我们真正学习并理解我们在做什么以及为什么要做,我们就可以得到帮助并询问他人。所以我要求这样做是为了帮助我理解为什么我的程序不会输出人名。

我想做的是;输入一个包含大写和小写字母的名称"lEonArDo DA vINCi",以及他们的出生日期"1520",然后输入代码,将该名称转换为小写并仅大写单词中的第一个字母,最后输出该名称。

我一直在输出这个名字。我就是不明白我做错了什么。我问过班上的其他人,但他们还在第一部分,或者在某种程度上被问题卡住了。

class Person{ //Can't change from here.
public:
    Person(string n, int year) : name(n), yearOfBirth(year){}
    string getName();
    friend ostream& operator <<(ostream&, const Person&);
private:
    string name; int yearOfBirth;
}; // to here.
string Person::getName() //output the name
{
    // I think the output should be here but it doesn't work.
    // I have also switched the code in the operator into the getName put it still doesn't work.
    return name;
}
ostream& operator << (ostream& output, const Person& P){ //turns everything into lowercase.
    locale loc;
    string temp = ""; //well be asigning the lowercase letters here; one at a time.
    int ii = 0;
    for (string::size_type i = 0; i < P.name.length(); i++) { //reads the input one at a time.
        if ((ii == 0) || (ii >= 1 && ((P.name[i - 1]) == char(32)))) {(toupper(P.name[i], loc), (temp += toupper(P.name[i], loc))); }//if it was lowercase and the first letter, it turns it into uppercase and assigns it to temp.
        else (tolower(P.name[i], loc), (temp += tolower(P.name[i], loc))); //if it was uppercase it turns it into lowercase and assigns it to temp.
        ii++;
    } //name = temp; //assigns the full lowercase word back to input01.*/
    output << temp << " was born in " << P.yearOfBirth;
    return output;
}
int main(){
    Person::Person("lEonArDo DA vINCi", 1520);
    // I have tried putting a output statement here as well
    return 0;
}

所以,我的问题是;我应该如何输出名称?(即cout.),我需要把输出语句放在哪里?(在getName或main函数中。)即使你能告诉我一个模糊的答案,它应该在哪里,也会对我有很大帮助。很抱歉我问了一个愚蠢的问题,浪费了你的时间。

Person::Person("lEonArDo DA vINCi", 1520);

不是一个人。你想要的是更多的

Person leonardo("lEonArDo DA vINCi", 1520);

这生成了一个名为leonardo的类型为Person的变量,并用"lEonArDo DA vINCi", 1520对其进行初始化。则可以使用CCD_ 4来访问该CCD_。例如,获取并打印名称

std::cout << leonardo.getName() << std::endl;

或者,由于您已经具有<lt;过载,

std::cout << leonardo <<std::endl;

使用运算符<lt;作用

您可能希望将大写规则从<lt;运算符转换为CCD_ 6构造函数。通过这种方式,您可以存储正确的版本,并在<lt;操作人员这使得<lt;操作要简单得多,并且在构造时只需运行一次校正,而不是每次打印。