我已经看到,为了检查类型T是否是我可以使用的类:
bool isClass = std::is_class<T>::value;
Run Code Online (Sandbox Code Playgroud)
它对类和结构都返回true.我知道在C++中它们几乎是一样的,但我想知道为什么在类型特征中它们之间没有区别.检查这种差异总是没用,还是有一些我不理解的理由?
我觉得这可能与C语法有关,但我用C++开始编程,所以我不确定.
基本上我已经看到了这个:
struct tm t;
memset( &t, 0, sizeof(struct tm) );
Run Code Online (Sandbox Code Playgroud)
我对这种语法有点困惑,因为通常我希望上面的内容看起来像这样:
tm t;
memset( &t, 0, sizeof(tm) );
Run Code Online (Sandbox Code Playgroud)
这两者之间有什么区别,为什么要使用前者呢?
tm我所指的结构是wchar.h,其定义如下:
struct tm {
int tm_sec; /* seconds after the minute - [0,59] */
int tm_min; /* minutes after the hour - [0,59] */
int tm_hour; /* hours since midnight - [0,23] */
int tm_mday; /* day of the month - [1,31] */
int tm_mon; /* months since January - [0,11] */
int tm_year; /* years …Run Code Online (Sandbox Code Playgroud) 我有以下代码(涉及多个文件)...
//--- 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用作模板参数这一事实与它有关。
感谢您的帮助。
要声明一个类对象,我们需要这种格式
classname objectname;
Run Code Online (Sandbox Code Playgroud)
声明结构对象是否相同?
喜欢
structname objectname;
Run Code Online (Sandbox Code Playgroud)
struct Books Book1;
Run Code Online (Sandbox Code Playgroud)
其中Books是结构名称,Book1是其对象名称.那么struct在声明结构对象之前是否需要使用关键字?