【发布时间】:2013-07-11 14:33:13
【问题描述】:
我正在尝试通过使用接口来创建一个非常模块化的程序。来自 C# 背景,我会将接口用作变量类型,这样我就可以使用多态性,允许我自己/其他人将从该接口继承的许多不同对象传递给函数/变量。 但是,尝试在 C++ 中执行此操作时,我遇到了许多奇怪的错误。我在这里做错了什么?
我希望能够拥有接口类型的变量。但是,以下会产生编译错误。我认为编译器认为我的 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
ErrorLogger.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
编译错误:
谢谢, -弗朗西斯科
【问题讨论】:
-
在 C++ 中,多态性需要使用指针(可能是智能指针)或引用。
-
编译错误很小。你能把它们作为纯文本而不是图片吗?
-
请发布实际代码而不是图片。
-
@CaptainObvlious:好吧,即使你的课程是具体的并且你做了
Derived d; Base b = d,你得到的是切片。所以是的,在这种情况下,问题还在于Base是抽象的,但这只是故事的一半;) -
正如@CaptainObvlious 所说,文本形式的实际代码很有帮助。原因是我们可以用鼠标把它捡起来,粘贴到一个测试 *.cpp 文件中,在回答之前自己尝试一下。
标签: c++ interface implementation