gpt4 book ai didi

c++ - 成员(member)使用无效

转载 作者:行者123 更新时间:2023-11-30 04:18:18 26 4
gpt4 key购买 nike

我想在静态函数 dayInMonths() 中调用数组的一个字段,但编译器告诉我“在静态函数中无效使用成员 Date::m_months” .我不知道 :( 我做错了什么。

.h

class Date
{
public:
..
Months* m_months;
..
public:
Date(..,unsigned int months=0,..);
~Date();

public:
static Days daysInMonth(unsigned int days);
};

class Months
{
public:
unsigned int m_months;
unsigned int m_monthsArray[13];
public:
Months(unsigned int months = 0);
..

日期.cpp

Date::Date(unsigned int days, unsigned int months, unsigned int years)
{

..
m_months->m_months = months;
..
}

Days Date::daysInMonth(unsigned int days=0){
return m_months.m_monthsArray[days];
}

月.cpp

Months::Months(unsigned int months)
{
m_months = months;
m_monthsArray[0] = 29;
m_monthsArray[1] = 31;
...

最佳答案

静态成员函数没有this。还有这条线

return m_months.m_monthsArray[days];

相当于

return this->m_months.m_monthsArray[days];

但是 daysInMonth 是一个静态函数。静态成员函数由类的所有实例共享,并且只能访问静态成员枚举数和类的嵌套类型的名称声明它的类

如果您希望 daysInMonth 对非静态成员进行操作,则不应将其设为静态。


public:
Days daysInMonth(unsigned int days);

现在它可以根据它所属的对象对成员进行操作。


一般来说,如果你没有静态成员变量,那么你可能不需要静态成员函数(除了为了封装)。

关于c++ - 成员(member)使用无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16497885/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com