如何在C++函数中访问类方法

How to access class method in C++ function

本文关键字:访问 类方法 函数 C++      更新时间:2023-10-16

我正在编写一个simlpe c ++程序,该程序使用ctime库显示当前日期,并要求用户输入任何年份以将其与当前年份进行比较。之后,它显示"有效"(如果输入年份小于当前年份)或"无效"(如果输入年份大于当前年份)。但是我遇到了一个我自己无法解决的问题。每次弹出错误时:无法在没有对象的情况下调用成员功能。代码如下:主.cpp

#include <iostream>
#include "header.h"    
using namespace std;    
void date();
int main()
{
    Header aCl;
    aCl.setYear(2010)
    int year;
    cin >> year;
    aCl.isValid()
}

函数.cpp

#include <ctime>
#include <iostream>
#include <string.h>
#include "header.h"
using namespace std;
void Header::setYear(int val){
    year = val;
}
void Header::isValid(int &passed)
{
    if (passed > Header::year)
        cout << "Valid" << endl;
    else
        cout <<"Invalid!" << endl;
}

void date(){
    time_t t = time(0);
    struct tm *now = localtime(&t);
    int currYear = now->tm_year + 1900; // Year is # years since 1900
    cout << "Current date is " << currYear << endl;
    Header::isValid(currYear);
}

标题.h

#ifndef HEADER_H
#define HEADER_H

#include <iostream>
#include <string.h>
using namespace std;
class Header {
    public:
        int year;
        void setYear(int val);
        void isValid(int &passed);
};
#endif 
aCl.isValid()

应该是:

aCl.isValid(year);

void Header::isValid(int &passed)
{
    if (passed > Header::year)
        cout << "Valid" << endl;
    else
        cout <<"Invalid!" << endl;
}

应该是:

void Header::isValid(int &passed)
{
    if (passed > year)
        cout << "Valid" << endl;
    else
        cout <<"Invalid!" << endl;
}

我对你的意图做了一些假设,但我认为这很可能是你的意思。