首页 > 解决方案 > 未在此范围内声明的类变量错误 c++

问题描述

DisplayValues()在这个程序中的功能有问题。首先,我被要求只为类中的函数编写原型。第二个要求是将整个函数DisplayValues()放在类之外。DisplayValues()是一个 const 内联成员函数。

以上所有内容都需要在头文件中。我在下面写了"'accountType' not declared in this scope"DisplayValues()函数并出现错误。我确实搜索了解决方案,但没有修改上述要求。有人可以建议吗?

我的代码:

文件 SavingsAccount.h

ifndef SAVINGSACCOUNT_H
#define SAVINGSACCOUNT_H

class SavingsAccount
{
    private:
        int accountType;

    public:
        inline void DisplayValues() const;
};

inline void DisplayValues() 
{
    cout << "Account type: " << accountType << '\n'
}
#endif //SAVINGSACCOUNT_H

文件 SavingsAccount.cpp

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

using namespace std;

void SavingsAccount::GetInitialValues()
{
    cout << "Enter account type:\n";
    cin >> accountType;   
}

文件 main.cpp

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

using namespace std;

int main()
{
    SavingsAccount ac;
    ac.GetInitialValues();
    ac.DisplayValues();
    
    return 0;
}

标签: c++

解决方案


我可以看到您的代码有 3 个明显的问题:

  1. 这是一个自由函数,而不是类成员函数
inline void DisplayValues() 
{
    cout << "Account type: " << accountType << '\n'
}

使固定:

inline void SavingsAccount::DisplayValues() 
{
    cout << "Account type: " << accountType << '\n'
}
  1. 您的声明inline void DisplayValues() const;,但定义缺少const关键字。
inline void SavingsAccount::DisplayValues() 
                                            ^^^^^ const missing here
  1. 您缺少分号是这一行:
    cout << "Account type: " << accountType << '\n'
                                                   ^^ semicolon missing here

推荐阅读