【问题标题】:Trying to access private class variables in header function试图访问头函数中的私有类变量
【发布时间】:2022-01-08 00:05:14
【问题描述】:

我需要一个头文件中的几个函数,这些函数使用std::cout 来表示日期,但我不知道如何从头文件中访问它们。如果我在课堂上,我可以说这样的话:

 void  DisplayStandard()
    {
        cout << month << "/" << day << "/" << year << endl;
    }

但是,由于我正在访问月、日和年(它们在我的 .cpp 文件中是私有的),因此我不确定如何从实现文件中的 void 函数修改它们。这是所有代码:

dateclasses.h

#ifndef DATECLASS_H
#define DATECLASS_H

class dateclass
{
    private:
        int month;
        int day;
        int year;
    public:
        //default constructor
        dateclass()
        {
            month = 1;
            day = 1;
            year = 1;
        }
        //value constructor
        dateclass(int month, int day, int year) 
        {
            this->month = month;
            this->day = day;
            this->year = year;
        }
        void DisplayStandard(); 
    
};
#endif

日期类.cpp

#include "dateclass.h"
#include <iostream>

using namespace std;

void DisplayStandard()
{
    cout << "Date: " << month << "/" << day << "/" << year << endl;
}   

我还没有设置主要功能,虽然我认为没有必要

【问题讨论】:

  • void DisplayStandard() { ... } 定义了一个 成员函数。你的书或教程是如何定义类成员函数的?
  • 使用dateclass::DisplayStandard来引用成员函数。

标签: c++ class header-files


【解决方案1】:

您可以通过将void DisplayStandard() 更改为void dateclass::DisplayStandard()解决此问题,如下所示

void dateclass::DisplayStandard()//note the dateclass:: added infront of DisplayStandard
{
    cout << "Date: " << month << "/" << day << "/" << year << endl;
} 

【讨论】:

  • 谢谢!这是我第二次参加这门课程,头文件对我来说从来没有意义——非常有帮助
猜你喜欢
  • 2015-09-25
  • 1970-01-01
  • 2011-11-05
  • 2013-08-06
  • 2015-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-29
相关资源
最近更新 更多