【发布时间】: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;
【问题讨论】:
-
Mother::age 是否应该设置为
this->ag?现在你只需退回它。 -
对不起,我没看懂你们的cmets,能详细点吗?谢谢!
-
如果您不理解我的评论,听起来您需要进一步学习 C++。在了解继承之前,您应该了解对象、变量、值和方法。
-
离题:标题中的
using namespace std;通常是个坏主意。现在,包括头球在内的每个人都必须应对后果。什么后果?在这里阅读更多:stackoverflow.com/questions/1452721/… -
离题:Mother.hpp 缺少包括警卫。这会造成无法估量的破坏。更多:stackoverflow.com/questions/21090041/why-include-guards 和这里:stackoverflow.com/questions/8020113/c-include-guards
标签: c++