实现文件无法从C ++头文件中识别类名

时间:2016-12-23 09:20:47

标签: c++ visual-c++

我正在学习C ++。我正在练习将我的C ++类拆分为单独的文件 - 实现和头文件,即 Student_Impl.cpp Student_Header.h 。然后有一个驱动程序文件 Student_register.cpp ,它将创建3个Student对象。但是,当我尝试构建它时,它会抛出错误,指出Student不是命名空间或类。我在我的实现文件Student_Impl.cpp和驱动程序文件Student_register.cpp中包含了Student_Header.h(其中存在Student类声明),但它仍然抛出相同的错误。可能的原因是什么?我正在使用Visual Studio 2015.

Student_Header.h

#pragma once
#include <string>
using namespace std;

class Student {
private:
    string fname;
    string lname;
    string address;
    string city;
    string phone;
    int age;

public:
    Student();
    Student(string, string, string, string, string, int);
    ~Student();
    string get_fname();
    string get_lname();
    string get_address();
    string get_city();
    string get_phone();
    int get_age();
};

Student_Impl.cpp

    #include "Student_Header.h"
    #include "iostream"
    #include "stdafx.h"
    #include <string>
    using namespace std;

    Student::Student()
    {

    }

    Student::Student(string fname1, string lname1, string address1, string city1, string phone1, int age1)
    {
        fname = fname1;
        lname = lname1;
        address = address1;
        city = city1;
        phone = phone1;
        age = age1;
    }

    string Student::get_fname()
    {
        return fname;
    }

    string Student::get_lname()
    {
        return lname;
    }

    string Student::get_address()
    {
        return address;
    }

    string Student::get_city()
    {
        return city;
    }

    string Student::get_phone()
    {
        return phone;
    }

    int Student::get_age()
    {
        return age;
    }


    Student::~Student()
    {}

Student_register.cpp

#include "stdafx.h"
#include "Student_Header.h"
#include <string>
#include "iostream"
using namespace std;

int main()
{
    Student Student1("Mike", "J", "MikeAdd", "MikeCity", "MikePhone", 26);
    Student Student2("Jack", "R", "JackAdd", "JackCity", "JackPhone", 25);
    Student Student3("Roney", "M", "RoneyAdd", "RoneyCity", "RoneyPhone", 27);

    // code for data retrieval

    return 0;
}

1 个答案:

答案 0 :(得分:0)

Marvin Sielenkemper在评论中添加了正确答案 - 忽略了之前到“stdafx.h”的标题。这是预编译头如何在Visual Studio上工作的特定于实现的副作用。

另外,请使用#include <iostream>代替#include "iostream"<header>表单适用于标准标头,"header.h"适用于您自己的标头。