C++接口(interface)声明/定义和使用

标签 c++ interface implementation

我正在尝试通过使用接口(interface)来创建一个非常模块化的程序。来自 C# 背景,我会使用接口(interface)作为变量类型,这样我就可以使用多态性,允许我自己/其他人将从这个接口(interface)继承的许多不同对象传递到一个函数/变量中。 但是,在 C++ 中尝试执行此操作时出现许多奇怪的错误。我在这里做错了什么?

我希望能够拥有接口(interface)类型的变量。但是,以下会产生编译错误。我认为编译器认为我的 ErrorLogger 类是抽象的,因为它继承自抽象类或其他东西。

ILogger * errorLogger = ErrorLogger();

error C2440: 'initializing' : cannot convert from 'automation::ErrorLogger' to 'automation::ILogger *'

如果我以错误的方式解决这个问题,即使是在设计方面,我也会学习并乐于听取任何和所有建议。

ILogger.h:

#ifndef _ILOGGER_H_
#define _ILOGGER_H_

namespace automation
{
    class ILogger
    {
    public:
        virtual void Log(const IError &error) = 0;
    };
}
#endif

ErrorLogger.h:

#ifndef _ERRORLOGGER_H_
#define _ERRORLOGGER_H_
#include "ILogger.h"
#include "IError.h"

/* Writes unhandled errors to a memory-mapped file.
 * 
**/

namespace automation
{
    class ErrorLogger : public ILogger
    {
    public:
        ErrorLogger(const wchar_t * file = nullptr, const FILE * stream = nullptr);
        ~ErrorLogger(void);
        void Log(const IError &error);
    };
}
#endif

错误记录器.cpp:

#include "stdafx.h"
#include "ErrorLogger.h"
#include "IError.h"

using namespace automation;

ErrorLogger::ErrorLogger(const wchar_t * file, const FILE * stream)
{

}

void ErrorLogger::Log(const IError &error)
{
    wprintf_s(L"ILogger->ErrorLogger.Log()");
}

ErrorLogger::~ErrorLogger(void)
{
}

IError.h:

#ifndef _IERROR_H_
#define _IERROR_H_

namespace automation
{
    class IError
    {
    public:
        virtual const wchar_t *GetErrorMessage() = 0;
        virtual const int &GetLineNumber() = 0;
    };
}
#endif

编译错误:

enter image description here

谢谢, -弗朗西斯科

最佳答案

ILogger * errorLogger = ErrorLogger(); errorLogger是一个指针,需要用new operator初始化。

定义指向派生类的基指针的正确方法是:

automation::ILogger * errorLogger = new automation::ErrorLogger();
//                                  ^^^^

在现代 C++ 中更好地使用智能指针:

#include <memory>
std::unique_ptr<automation::ILogger> errorLoggerPtr(new automation::ErrorLogger());

你还需要在 ILogger.h 中包含 IError.h

#include "IError.h"

其他建议:

1 使用fstream 代替FILE 2 使用 std::wstring 而不是 wchar_t * 2在cpp文件中,不要调用

using namespace automation;

而是用命名空间包装函数定义,就像您在头文件中所做的那样:

namespace automation
{
    ErrorLogger::ErrorLogger(const std::wstring& file, std::ofstream& stream)
    {
    }
}

重点是不要将 C++ 代码与 C 代码混合,C++ 类如字符串,fstream 提供 RAII ,更安全,更易于使用。

关于C++接口(interface)声明/定义和使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17625252/

相关文章:

c++ - c++链表不再占用Ram空间?

c++ - 在 C++ 中更新静态函数中的非静态成员

javascript - 如何让基本泛型类型知道 TypeScript 中的子泛型?

java - 方法签名声明为 throws Exception;实现为抛出 Exception 的子类

返回接口(interface)类型的 Java 方法

c++ - 适应 Boyer-Moore 实现

c++ - 为什么在此代码中出现运行时错误SIGSEGV

c++ - 指针中的二维数组

C#泛型,传递类

.net - WCF中契约(Contract)的继承