【问题标题】:C++ define class in head file, and implement its member in source fileC++在头文件中定义类,并在源文件中实现其成员
【发布时间】:2013-11-16 01:41:37
【问题描述】:

当我在 vs2010 中构建这个项目时,出现错误:

  1. 语法错误:缺少';'在标识符“b”之前
  2. 错误 C4430:缺少类型说明符 - 假定为 int。注意:C++ 可以 不支持默认整数
  3. 错误 C4430:缺少类型说明符 - 假定为 int。笔记: C++ 不支持默认整数
  4. 错误 C2065:“b”:未声明的标识符

    #ifndef _B_H
    #define _B_H
    
    #include <string>
    
    class B
    {
    public:
        B();
        ~B();
        void showfunc();
    
        string b;
    };
    
    #endif
    
    /***************************/
    // B.cpp
    #include <iostream>
    #include <string>
    #include "B.h"
    using namespace std;
    B::B()
    {
    }
    void B::showfunc()
    {
     cout<<b<<endl;
    }
    /**************************************/
    // main.cpp
    #include <iostream>
    // #include "B.h"
    using namespace std;
    void main()
    { 
    }
    

请帮帮我!

【问题讨论】:

  • string 位于 std 命名空间中。你需要std::string b;

标签: c++


【解决方案1】:

string 位于 std 命名空间中。你需要

std::string b; 

你也应该是be careful with using namespace std,即使在实现文件中。

另外,请注意void main() 不是 C++ 中main 的标准签名之一。你需要

int main() { ...

【讨论】:

  • 我在头文件B.h的开头添加了using namespace std;,它可以工作。在 std 命名空间中使用类时,每次都添加 std 前缀很麻烦。但实际上我在源文件 B.cpp 的头部有 using namespace std; 语句。为什么它不起作用?
  • @Barnett_Love 你不应该使用using namespace std。麻烦多于其价值。有一天你会深深地后悔。至于你的问题,把它放在B.cppB.h 没有影响。
【解决方案2】:

std 添加到字符串

std::string b;

【讨论】:

  • 非常感谢。我在头文件B.h的开头添加了using namespace std;,它可以工作了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-05
  • 2011-08-24
  • 1970-01-01
  • 2014-01-28
  • 1970-01-01
相关资源
最近更新 更多