C ++ / VS2005:在两个不同的.cpp文件中定义相同的类名 [英] C++/VS2005: Defining the same class name in two different .cpp files

查看:550
本文介绍了C ++ / VS2005:在两个不同的.cpp文件中定义相同的类名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我的单元测试框架(UnitTest ++)允许你创建结构体来作为一个单元测试。夹具。通常这些都是自定义的文件中的测试,所以我把它们放在我的单元测试文件的顶部。

  // Tests1.cpp 

struct MyFixture {MyFixture(){...做一些设置事情...}};

TEST_FIXTURE(MyFixture,SomeTest)
{
...
}

//Tests2.cpp

struct MyFixture {MyFixture(){...做一些其他的设置事情,不同于Tests1}};

TEST_FIXTURE(MyFixture,SomeOtherTest)
{
...
}

$但是,我最近发现(用VS2005至少),当你命名fixture结构使用相同的名称(所以现在两个版本的结构存在相同的名称),然后其中一个版本被静静抛出。这是非常令人惊讶的,因为我有我的编译器设置为/ W4(最高警告级别),没有警告出来。我猜这是一个名称冲突,为什么命名空间是发明,但我真的需要包装我的单元测试夹具在一个单独的命名空间?我只是想确保我不缺少更基本的东西。



有更好的方法来解决这个问题 - 这应该发生吗?

解决方案

尝试在匿名命名空间中粘贴类,您可能会发现它不必为每个文件创建和命名一个新的命名空间。



没有访问VS2005和Cpp单元,但这可能工作..

  // Tests1.cpp 
namespace
{
struct MyFixture {MyFixture(){...做一些设置事情...}};
}

TEST_FIXTURE(MyFixture,SomeTest)
{
...
}


Tests2.cpp
namespace
{
struct MyFixture {MyFixture(){...做一些其他的设置事情,不同于Tests1}};
}

TEST_FIXTURE(MyFixture,SomeOtherTest)
{
...
}


Somewhat of an academic question, but I ran into this while writing some unit tests.

My unit test framework (UnitTest++) allows you to create structs to serve as fixtures. Usually these are customized to the tests in the file, so I put them at the top of my unit test file.

//Tests1.cpp

struct MyFixture {  MyFixture() { ... do some setup things ...} };

TEST_FIXTURE(MyFixture, SomeTest)
{
  ...
} 

//Tests2.cpp

struct MyFixture { MyFixture() { ... do some other setup things, different from Tests1}};

 TEST_FIXTURE(MyFixture, SomeOtherTest)
 {
  ...
 }

However, I found recently (with VS2005 at least) that when you name the fixture struct using the same name (so now two versions of the struct exist with the same name), then one of the versions is silently thrown out. This is pretty surprising, because I have my compiler set to /W4 (highest warning level) and no warning comes out. I guess this is a name clash, and why namespaces were invented, but do I really need to wrap each of my unit test fixtures in a separate namespace? I just want to make sure I'm not missing something more fundamental.

Is there a better way to fix this - should this be happening? Shouldn't I be seeing a duplicate symbols error or something?

解决方案

Try sticking the classes in an anonymous namespace, you may find it less distasteful than having to create and name a new namespace for each file.

Don't have access to VS2005 and Cpp unit but this may work..

//Tests1.cpp
namespace
{
struct MyFixture {  MyFixture() { ... do some setup things ...} };
}

TEST_FIXTURE(MyFixture, SomeTest)
{
  ...
} 


//Tests2.cpp
namespace
{
struct MyFixture { MyFixture() { ... do some other setup things, different from Tests1}};
}

TEST_FIXTURE(MyFixture, SomeOtherTest)
{
 ...
}

这篇关于C ++ / VS2005:在两个不同的.cpp文件中定义相同的类名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆