如何在C++函数中访问类方法
How to access class method in C++ function
我正在编写一个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;
}
我对你的意图做了一些假设,但我认为这很可能是你的意思。
相关文章:
- 如何访问由共享指针保存的类方法?
- 初始化指向类实例的智能指针并访问其方法
- 访问类成员向量最后一项的正确方法
- 使用基类对象访问派生的仅类方法
- 无法访问派生类中的基类方法
- 类变量无法从类方法访问
- 如果指针的子类的方法对于子类是唯一的,如何访问这些方法?
- 从C++中的父类实例访问子类方法
- C++ 如何使用类方法正确访问动态数组元素
- 抽象类的需求是什么?为什么要通过其基类访问派生类方法?在C++
- C++11 纯虚拟类的朋友无法访问私有方法
- 调用不访问已删除对象中的任何类成员的类方法是否安全
- C++是否提供了一种在没有范围解析运算符的情况下访问类中的类的方法?
- 为什么父类的父类方法在没有显式范围解析的情况下无法访问?
- 访问类方法中的私有指针变量C++
- 访问指针数组中的子类方法
- C - 函数能够访问类方法,而不会创建静态或对象
- 如何访问友元类方法?
- 如何在C++函数中访问类方法
- 当从不同位置访问类方法时,类成员的位置会发生变化