相关疑难解决方法(0)

混合类和结构

我很清楚类和结构之间区别,但是我很难权威地说这是否定义得很好:

// declare foo (struct)
struct foo;

// define foo (class)
class foo {
};

// instance of foo, claiming to be a struct again! Well defined?
struct foo bar;

// mixing class and struct like this upsets at least one compiler (names are mangled differently)
const foo& test() {
   return bar;
}

int main() {
   test();
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

如果这是未定义的行为,有人可以指向权威(即ISO的章节和经文)参考的方向吗?

处理这个问题的编译器(Carbide 2.7)相对较旧,我尝试过的所有其他编译器对此都非常满意,但显然没有任何证据.

我的直觉是这应该是未定义的行为,但我找不到任何证实这一点,我很惊讶没有GCC版本或Comeau这么多警告它.

c++ struct class undefined-behavior

17
推荐指数
2
解决办法
2951
查看次数

为什么要在类对象的声明中写一个“类”?

我通常不会这样写,但我见过一个代码库几乎无处不在,例如:

class prettyClass
{
    // just class stuff
};

int main()
{
    class prettyClass obj; // class?
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

c++ oop

10
推荐指数
1
解决办法
867
查看次数

向前将结构声明为类时出现Visual C ++ 2015链接器错误

我有以下代码(涉及多个文件)...

//--- SomeInterface.h
struct SomeInterface
{
  virtual void foo() = 0;
  virtual ~SomeInterface(){}
};

//--- SomeInterfaceUser.h
#include <memory> //shared_ptr

class SomeInterface;
//NOTE: struct SomeInterface... causes linker error to go away...

class SomeInterfaceUser
{
  public:
    explicit SomeInterfaceUser(std::shared_ptr<SomeInterface> s);
};

//SomeInterfaceUser.cpp
#include "SomeInterfaceUser.h"
#include "SomeInterface.h"
SomeInterfaceUser::SomeInterfaceUser(std::shared_ptr<SomeInterface> s)
{
}

//SomerInterfaceUserInstantiator.cpp
#include "SomeInterfaceUser.h"
#include "SomeInterfaceImpl.h"

struct SomeInterfaceImpl : SomeInterface
{
  virtual void foo(){}
};

void test()
{
  SomeInterfaceUser x{std::make_shared<SomeInterfaceImpl>()};
}
Run Code Online (Sandbox Code Playgroud)

使用Visual C ++编译器,我得到一个链接器错误(LNK2019)。使用GCC 4.8.4并非如此。将前向声明类SomeInterface更改为struct SomeInterface可使链接器错误消失。我一直以为应该可以互换使用类/结构?SomeInterfaceUser的接口不应取决于SomeInterface是定义为类还是struct,不是吗?

这是Visual C ++错误吗?我找不到任何与此有关的东西。我怀疑将struct用作模板参数这一事实与它有关。

感谢您的帮助。

c++ visual-c++

6
推荐指数
1
解决办法
731
查看次数

标签 统计

c++ ×3

class ×1

oop ×1

struct ×1

undefined-behavior ×1

visual-c++ ×1