c++ - 错误:使用类文件时未在此范围内声明“x”
问题描述
我在使用类文件时遇到问题,编译器错误提示“错误:未在此代码上声明'x'”,同时指出 cout、字符串和 endl。我已经在头文件、类和主文件中写了“#include”和“#include”。
(对不起我的英语)我只是一个初学者,我想知道基础知识
在两个文件中添加了#include 和#include
//Main File (main.cpp)
#include <iostream>
#include "test.h"
#include <string>
using namespace std;
int main()
{
test *person = new person("Phroton",14)
person.Display();
return 0;
}
//test.h
#ifndef TEST_H
#define TEST_H
#include <iostream>
#include <string>
class test
{
private:
string name;
int age;
public:
void Display(){
cout << "I'm " << name << " and I'm " << age << "years old" << endl;
}
};
#endif // TEST_H
//test.cpp (There is no problem with this file at all)
#include "test.h"
#include <iostream>
#include <string>
test::test(string iname, int iage)
{
name = new string;
age = new int;
*name = iname;
*age = iage;
}
test::~test()
{
delete name;
delete age;
cout << "Info Deleted" << endl;
}
解决方案
回答您提出的具体问题:
这是因为你没有在文件中指定命名空间cout
和endl
所属test.h
。
中的声明Display
应该是:
std::cout << "I'm " << name << " and I'm " << age << "years old" << std::endl;
对此的替代方法是using namespace std
声明,但这被认为是一种不好的做法(尤其是在头文件中)。
笔记:
您不需要
using namespace std
in,main.cpp
因为您没有使用std
那里命名空间中的任何函数。即使你这样做了,也要使用std::name
而不是using
声明。成员函数定义通常存在于 .
cpp
文件。因此,您可以将函数定义Display
为test.cpp
.还可以考虑从原始指针转向智能指针。
推荐阅读
- sql-server - 日期字段计算不一致
- php - Group and display MYSQL rows by day?
- python - Pygame Resisable Bounding Box for Player
- java - 如何在硒中捕获多个段落标签的所有包装文本?
- c# - 在 Fody 的开放泛型中添加对泛型方法的调用
- hibernate - 如何在 Grails 3 中覆盖 DomainClass getter
- arrays - 给定范围的数组的最小连续和
- python - 如何使用python提取和打印表格中所有标签内的文本
- html - HTML / CSS - 箭头在轮播下方
- python - 值错误:无法将字符串转换为浮点数:“男性”