c++ - 未在此范围内声明的类变量错误 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;
}
解决方案
我可以看到您的代码有 3 个明显的问题:
- 这是一个自由函数,而不是类成员函数。
inline void DisplayValues()
{
cout << "Account type: " << accountType << '\n'
}
使固定:
inline void SavingsAccount::DisplayValues()
{
cout << "Account type: " << accountType << '\n'
}
- 您的声明是
inline void DisplayValues() const;
,但定义缺少const
关键字。
inline void SavingsAccount::DisplayValues()
^^^^^ const missing here
- 您缺少分号是这一行:
cout << "Account type: " << accountType << '\n'
^^ semicolon missing here
推荐阅读
- python-3.x - leetcode 88 合并排序数组 python3 切片问题
- swift - 通过对象的枚举属性使用 NSPredicate 获取核心数据托管对象的问题
- c# - Moq 成员变量不会因设置无效而引发错误
- c# - RESTful API - 为每个实体创建“服务”和“接口”?
- r - 创建一个函数,不小心覆盖了输出
- bash - bash 变量替换和引用
- android - MaterialComponents 主题中断 TabLayout
- python - 如何在 python 中解析包含 HTML 代码的 XLS 文件?
- c# - .net 核心复选框模型绑定视图
- r - 在 R 中使用 ggtext 和 gridtext 在 R 中具有跨越图例的多面板图