【问题标题】:Issue with name of the class or namespace类或命名空间的名称问题
【发布时间】:2016-05-31 11:04:21
【问题描述】:

编译器说:students 不是类或命名空间的名称。它说“名称”是未声明的。

students.cpp:

    #include "stdafx.h"
#include <string>
#include "students.h"
using namespace std;
    void students::set_name(string student_name)
    {
        name = student_name;
    }

students.h:

#pragma once
#include <string>
#include "students.cpp"
using namespace std;
class students
{   public:
            void set_name(string student_name); 
    private:
            string name;
};

main.cpp

#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <string>
#include "students.h"
#include "students.cpp"
using namespace std;  
    int main()
    {
        students *student = new students;
        std::string name;
        std::cout << "Name: ";
        getline(std::cin, name);
        student->set_name(name);
        delete student;
        system("pause");
        return 0;
    }

更新:在我删除“#include”students.cpp“”后,我得到了:

 1>students.obj : error LNK2005: "public: void __thiscall students::set_name(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >)" (?set_name@students@@QAEXV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z) уже определен в main.obj

【问题讨论】:

    标签: c++ class namespaces


    【解决方案1】:

    你不应该在students.h文件中包含.cpp文件,只是省略

    #include "students.cpp"
    

    附加提示:省略

    using namespace std;
    

    在头文件中避免命名空间冲突,见question here

    【讨论】:

      【解决方案2】:

      LNK2005 表示符号已定义,您已添加:

      #include "students.cpp"
      

      在您的源文件中的两个位置,因此您有多个students::set_name(string student_name) 定义。永远不要在源文件中包含 .cpp 文件。在您的项目中添加students.cpp,然后在您的源代码中删除所有出现的#include "students.cpp"

      【讨论】:

        【解决方案3】:

        您应该从 main.cpp 和 students.h 中删除 #include "students.cpp"

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-01-31
          • 1970-01-01
          • 2012-06-19
          • 1970-01-01
          相关资源
          最近更新 更多