做为C++的初学者,不知道错误在哪里


#include
using namespace std;
class Time
{
private:
    int hour;
    int minute;
    int sec;
public:
    void set_time();
    void show_time();
};

int main()
{
    Time t;
    t.set_time();
    t.show_time();
    return 0;
}
void Time::set_time()
{
    cin>>t.hour;
    cin>>t.minute;
    cin>>t.sec;
}
void Time::show_time()
{
    cout<":"<":<<"t.sec<

编译提示:
t1.cpp(23) : error C2065: 't' : undeclared identifier
t1.cpp(23) : error C2228: left of '.hour' must have class/struct/union type
t1.cpp(24) : error C2228: left of '.minute' must have class/struct/union type
t1.cpp(25) : error C2228: left of '.sec' must have class/struct/union type
t1.cpp(29) : error C2228: left of '.hour' must have class/struct/union type
t1.cpp(29) : error C2228: left of '.hour' must have class/struct/union type
t1.cpp(29) : error C2146: syntax error : missing ';' before identifier 't'
t1.cpp(29) : error C2228: left of '.sec' must have class/struct/union type
执行 cl.exe 时出错.

变量 t 是在 main() 函数里面说明的。 他在 Time::set_time() 里面是看不到的,因此你有 23 行的第一个错误。
建议把书上的例子重敲一遍,了解 类 / 作用域, 等概念。

cin>>t.hour;
这里错了
t是在main函数里定义的,这里没有定义呀
你应该直接写成hour或者this.hour

你这里面的t是??
void Time::show_time()
{
cout<<t.hour<<":"<<t.hour<<":<<"t.sec<<endl;
}

t是主函数定义的变量,类的成员函数不能直接调用。
类的成员函数都有一个隐藏的形参,这个参数叫this,指向了本身这个类。所以可以用this去直接访问成员变量。代码修改如下。


#include <iostream>

using namespace std;
class Time
{
private:
    int hour;
    int minute;
    int sec;

public:
    void set_time();
    void show_time();
};

int main()
{
    Time t;
    t.set_time();
    t.show_time();
    return 0;
}
void Time::set_time()
{
    cin >> this->hour;
    cin >> this->minute;
    cin >> this->sec;
}
void Time::show_time()
{
    cout << this->hour << ":" << this->minute << ":" << this->sec << endl;
}