对象作为函数参数

object as function argument

本文关键字:参数 函数 对象      更新时间:2023-10-16

我写了一个简单的程序。

我收到此错误:

time.cpp: In function ‘int main()’:
time.cpp:22:9: error: expected ‘;’ before ‘a’
time.cpp:23:4: error: ‘a’ was not declared in this scope
time.cpp:24:4: error: ‘b’ was not declared in this scope
time.cpp:25:4: error: ‘c’ was not declared in this scope

这是我的代码:

#include<iostream>
using namespace std;
class time
{
    int hour;
    int min;
public:
    void gettime(int h,int m)
    {
        hour=h;
        min=m;
    }
    void puttime()
    {
        cout<<hour<<endl<<min;
    }
    void sum(time x,time y)
    {
        min=x.min+y.min;
        hour=min/60;
        min=min%60;
        hour=hour+x.hour+y.hour;
    }
};
int main()
{
    time a,b,c;
    a.gettime(2,45);
    b.gettime(3,35);
    c.sum(a,b);
    a.puttime();
    b.putime();
    c.puttime();
    return 0;
}

请记住,有一个名为 time 的标准函数。

这是您应该避免using namespace std;的主要原因之一。

b.putime() 在这里必须是 b.puttime()。否则编译此代码