无法从函数返回值

Not able to return the value from a function

本文关键字:返回值 函数      更新时间:2023-10-16

我正在学习c++中的继承,并试图从函数"age"返回值。得到的结果是0。我花了好几个小时想弄明白,但运气不好。下面是我的代码。我将非常感谢任何帮助在这个!

. h类
#include <stdio.h>
#include <string>
using namespace std;
class Mother
{
public:
    Mother();
    Mother(double h);
    void setH(double h);
    double getH();
    //--message handler
    void print();
    void sayName();
    double age(double a);
private:
    double ag;
};

. cpp

#include <iostream>
#include <string>
#include "Mother.hpp"
#include "Daughter.hpp"
using namespace std;
Mother::Mother(){}
Mother::Mother(double h)
{
    ag=h;
}
void setH(double h){}
double getH();
void Mother::print(){
    cout<<"I am " <<ag <<endl;
}

void Mother::sayName(){
    cout<<"I am Sandy" <<endl;
}
double Mother::age(double a)
{
    return a;
}
主要

#include <iostream>
#include "Mother.hpp"
#include "Daughter.hpp"
using namespace std;
int main(int argc, const char * argv[]) {
    Mother mom;
    mom.sayName();
    mom.age(40);
    mom.print();
    //Daughter d;
    //d.sayName();
    return 0;

你的妈妈。print()这样做:

cout<<"I am " <<ag <<endl;

这里的问题是:ag = 0

你的妈妈年龄(40)这样做:

return a;

看,它不会把你妈妈的年龄保存到你的mom变量中,它只返回你传递的值(这里是40),所以它怎么能打印出来呢?

因此,有很多方法可以解决这个问题,如果你想返回你妈妈的年龄,做count <<年龄(40岁)主要()或者,只是:

void Mother::age(double a)
{
    ag = a;
}

函数age没有将值a赋值给成员ag,而是返回值a作为参数,这是一件很糟糕的事情。为了得到我想在main中说的话,写:

cout << mom.age(40) << endl; // 40

为使其正确,将函数年龄更改为:

double Mother::age(double a)
{
    ag = a;
    return a; // it's redundant to do so. change this function to return void as long as we don't need the return value
}

***你应该做的另一件事:

使"getter "为const以防止改变成员数据,只让"setter "为非常量。例如在你的代码中:class mother:

double getH()const; // instead of double getH() const prevents changing member data "ag" 

必须正确使用setter和getter。使用setter来更改年龄,如下所示:

void setAge(const double &_age) {
    ag = _age;
}

如果要检索值,请使用getter。

double getAge() const {
    return ag;
 }