首页 > 解决方案 > 错误:使用类文件时未在此范围内声明“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;
}

标签: c++

解决方案


回答您提出的具体问题:

这是因为你没有在文件中指定命名空间coutendl所属test.h

中的声明Display应该是:

std::cout << "I'm " << name << " and I'm " << age << "years old" << std::endl;

对此的替代方法是using namespace std声明,但这被认为是一种不好的做法(尤其是在头文件中)。

笔记:

  • 您不需要using namespace stdin,main.cpp因为您没有使用std那里命名空间中的任何函数。即使你这样做了,也要使用std::name而不是using声明。

  • 成员函数定义通常存在于 . cpp文件。因此,您可以将函数定义Displaytest.cpp.

  • 还可以考虑从原始指针转向智能指针。


推荐阅读