标题:可以在main函数中调用类中的变量么?
只看楼主
木头lbj
Rank: 7Rank: 7Rank: 7
来 自:黄山
等 级:黑侠
威 望:1
帖 子:269
专家分:527
注 册:2010-11-6
结帖率:100%
已结贴  问题点数:15 回复次数:2 
可以在main函数中调用类中的变量么?
#include <iostream>
using namespace std;
const int invest = 100;

class Daphne
{
private:
    int year1;
    float arrural1;
public:
    float benifit1;
    int sum1()
    {
        arrural1 = invest * 0.1;
        benifit1 = invest;
        for (year1 = 1; year1 < 100 ; year1 ++)
        {
            benifit1 += arrural1;
            cout << "The " << year1 << " year,Daphne's benifit is: " << benifit1 << endl;
        }
        return benifit1;
    }
};

class Cleo
{
private:
    int year2;
    float arrural2;
    float total;
public:
    float benifit2;
    int sum2()
    {
        benifit2 = invest;
        total = benifit2;
        for (year2 = 1; year2 < 100 ; year2 ++)
        {
            arrural2 = total * 0.05;
            total = benifit2 + arrural2;
            benifit2 += arrural2;
            cout << "The " << year2 << " year,Cleo's benifit is:\t " << benifit2 << endl;
        }
        return benifit2;
    }
};


int main()
{
    Daphne s1;
    Cleo s2;
    s1.sum1();
    s2.sum2();
   
    return 0;
}
程序的目的是想要输出什么时候Cleo的钱超过Daphne的。我想用类来实现。但是不知道在主函数中写判断Cleo超过Daphne时的语句。哪位大侠来指导下啊。。。
搜索更多相关主题的帖子: 变量 main 函数 
2010-12-16 15:21
zhangyasong
Rank: 2
等 级:论坛游民
帖 子:4
专家分:36
注 册:2008-12-31
得分:15 
#include <iostream>
using namespace std;
const int invest = 100;

class Daphne
{
private:
    int year1;
    float arrural1;
public:
    float benifit1;
    int sum1(int n)
    {
        arrural1 = invest * 0.1;
        benifit1 = invest;
        for (year1 = 1; year1 < n ; year1 ++)
        {
            benifit1 += arrural1;
            cout << "The " << year1 << " year,Daphne's benifit is: " << benifit1 << endl;
        }
        return benifit1;
    }
};

class Cleo
{
private:
    int year2;
    float arrural2;
    float total;
public:
    float benifit2;
    int sum2(int n)
    {
        benifit2 = invest;
        total = benifit2;
       for (year2 = 1; year2 < n ; year2 ++)
        {
            arrural2 = total * 0.05;
            total = benifit2 + arrural2;
            benifit2 += arrural2;
            cout << "The " << year2 << " year,Cleo's benifit is:\t " << benifit2 << endl;
        }
        return benifit2;
    }
};


int main()
{
    Daphne s1;
    Cleo s2;
    for(int i=2;i<100;++i)
{
    if(s1.sum1(i)<s2.sum2(i))
{
    cout<<"在第"<<i<<"年,Cleo的钱超过了Daphne的钱"<<endl;
    break;
}
}
   
    return 0;
}

随便改了下,主要是传了个表示年限的参数进去,不知道可不可以解决你的问题
2010-12-16 15:53
木头lbj
Rank: 7Rank: 7Rank: 7
来 自:黄山
等 级:黑侠
威 望:1
帖 子:269
专家分:527
注 册:2010-11-6
得分:0 
回复 2楼 zhangyasong
恩恩   可以解决。。。。谢谢啊。能向你请教这样做的原因么?我一时还弄不太懂

。。。!!!)))000
2010-12-16 16:41



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-329133-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.374779 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved