【问题标题】:linux eclipse c++ local namespaces and "std::"linux eclipse c++ 本地命名空间和“std::”
【发布时间】:2015-08-13 20:35:56
【问题描述】:

我想,我正在尝试我的第一个 c++ 项目,并且从小做起。我正在使用 Eclipse Luna,并试图在我可以的任何地方采用默认的构建环境。我怀疑以下是不同的幼稚代码,但您必须从某个地方开始。

我最终将有 4 个合作/子项目:

  1. 静态库的命令行界面
  2. “.so”库将被动态加载到不同的盗版应用程序中并使用静态库
  3. 上面提到的一个静态库,它执行组合应用程序的后端工作。
  4. 一个实用程序类(现在,以后可能是一个小库),用于其他子项目通用的实用程序类和函数。

关于最佳实践、命名空间等有很多问题我想问,但我会尽量简短。

我有以下 c++ 头文件:

/*
 * Utilities.h
 *
 */

#ifndef UTILITIES_H_
#define UTILITIES_H_

// A

namespace UserTrackingUtilities {
// B
#include <string>
#include <exception>
    using namespace std;

    class MyException: public std::exception {
        public:
            MyException(std::string ss) : s(ss) {
            }
            ~MyException() throw () {
            } // Updated

            std::string s;

            const char* what() const throw () {
                return s.c_str();
            }
    };
}

#endif /* UTILITIES_H_ */

这是一个异常实用程序(在不同的 StackOverflow 线程中找到),我将其包装在自己的命名空间中——我想。

Eclipse 显示此头文件存在几个问题。我将从一个开始:它不喜欢std::string 构造。我是否将#includes 和/或using 语句放在AB 点都没有关系。

我也尝试过使用 Linux GCC 和 ADT 工具链。

欢迎指点和建议。

【问题讨论】:

  • 不要将#include 语句放在命名空间内。当我将#includes 移动到指向A 时,您的代码对我来说编译得很好。
  • 别说using namespace std;
  • 带有 CDT 的 Eclipse Luna 和 Mars 可以很好地吃掉该文件,即使在位置 B 包含包含和 using namespace std;。顺便说一句,using namspace std; 死亡。

标签: c++ linux eclipse


【解决方案1】:
#include <string>
#include <exception>

应该在之前

namespace UserTrackingUtilities {

顺便说一句:

如果你使用using namespace std,你可以写string而不是std::string

但我建议不要使用 using namespace std 以避免名称冲突和歧义。

更新:

这是一个最小的工作示例:

#include <iostream>
#include <string>
#include <exception>

namespace UserTrackingUtilities {

    class MyException: public std::exception {
        public:
            MyException(std::string ss) : s(ss) {
            }
            ~MyException() throw () {
            } // Updated

            std::string s;

            const char* what() const throw () {
                return s.c_str();
            }
    };
}

int main()
{
    UserTrackingUtilities::MyException ex("Hello World");
    std::cout << ex.what() << std::endl; 
    return 0;
}

【讨论】:

  • 这让我的大脑受伤了。我将包含移动到点 A 并使用删除 std 命名空间。 std::string s; 告诉我‘string’ in namespace ‘std’ does not name a type
  • return s.c_str(); 行告诉我 s 未在此范围内定义。我认为我的日食已经结束了
  • @7Reeds 如果你得到一个编译器错误,这是非常非常非常非常非常非常少见的编译器或IDE的错误。
  • @7Reeds 听起来你的项目配置不正确。
  • @7Reeds 好像#include &lt;string&gt;有问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-01
  • 2020-08-21
  • 2016-04-01
  • 2016-07-10
  • 2018-02-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多