【问题标题】:Not able to return the value from a function [closed]无法从函数返回值[关闭]
【发布时间】:2016-09-23 23:55:13
【问题描述】:

我正在学习 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;

【问题讨论】:

标签: c++


【解决方案1】:

你的 mom.print() 会这样做:

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

所以这里的问题是:ag = 0

你的 mom.age(40) 会这样做:

return a;

看,它不会将你妈妈的年龄保存到你的 mom 变量中,它只返回你传递的内容(这里是 40 ),那么它怎么打印?

因此,有很多方法可以解决这个问题,如果你想返回你妈妈的年龄,在 main() 中执行 cout

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

【讨论】:

    【解决方案2】:

    函数 age 不会将值 a 分配给成员 ag 而是返回它作为参数的值 a 这是一件坏事。 得到我想说的主要写:

    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
    }
    

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

    将“getters”设为 const 以防止更改成员数据,并且只让“setters”不保持不变。例如在您的代码中:类妈妈:

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

    【讨论】:

    • 谢谢@Raindrop7。做到了!
    • @familyGuy 欢迎!如果有效,请将其作为可接受的答案
    【解决方案3】:

    您必须正确使用 setter 和 getter。使用 setter 像这样更改年龄:

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

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

    double getAge() const {
        return ag;
     }
    

    【讨论】:

      猜你喜欢
      • 2013-04-22
      • 2014-08-12
      • 2019-04-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-26
      • 2012-02-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多