【问题标题】:Error when a class inherites another class in a header file in c++当一个类在c ++的头文件中继承另一个类时出错
【发布时间】:2018-05-12 16:45:11
【问题描述】:

//头文件

#include <exception>
#ifndef CRYPTSERVEXCEPTION_H
#define CRYPTSERVEXCEPTION_H


class cryptServException
{
public:
//these are classes defined in a class 
class CantOpenForEncryption : public std::exception
{
public:

    const char* what();
};


class DecryptKeyMismatch : public std::exception
{

public :

const char* what();
};

#endif // CRYPTSERVEXCEPTION_H

有这个隐式构造函数给出错误我只是无法理解原因,因为我们可以将构造函数的主体留空,如果有一些代码可以放在其中我不知道它应该是什么,希望现在你有问题了。

//CPP文件

#include "cryptServException.h"
//rest are just classes that are for exceptions
 cryptServException::cryptServException()
 {
 // this constructor declaration gives the error : definition of implicitly- declared 'constexpr myException::myException()'|
 }
//this is just a class in another class
cryptServException::CantOpenForEncryption : public exception
{

public :

const char* what()
{
    return " Can't Open File For Encryption ";
}
};

//this is just a class in another class
cryptServException::DecryptKeyMismatch : public exception
{

public :

const char* what()
{
    return " Incorrect Decryption Key ";
}
};

我无法确定上述隐式构造函数的错误原因。

感谢帮助

您能否建议我是否在 .cpp 文件中添加一个构造函数,应该在它的主体中放置什么代码

【问题讨论】:

  • 名称exception在哪里定义?
  • 其实我是直接用c++的异常类
  • 但是您没有包含定义该类的标头。

标签: c++ c++11 constructor header


【解决方案1】:

该错误意味着编译器目前不知道exception 标记。它希望在此时看到一个类名,但是上面没有声明名为 exception 的类。

要修复它,请将#include &lt;exception&gt; 添加到您的头文件中(当然,如果您的意思是std::exception)。可能在您的源文件中间接包含此文件。

【讨论】:

  • 谢谢,这确实有效,但构造错误仍然存​​在,你能告诉我为什么这没有在 .cpp 文件中导致错误,我没有包含 exception.h
  • @Nilesh 您是否显示了导致错误的完整类?在这种情况下不应出现此错误。
  • 我发布的只是为了展示,实际代码有点长。但也不例外,myException 类包含 6 个不同的类,用于不同类型的异常。
  • @Nilesh “只是为了展示” - 你必须发布真实的代码来说明你的问题。
  • 请给我几秒钟
【解决方案2】:

解决办法是

  1. 从 cpp 文件中删除构造函数声明,我做错的是构造函数声明是自动生成的存根,我忽略了它。

  2. 也不需要在 .cpp 文件中声明类,只需使用方法的完整限定名并按照@WhozCraig 的建议实现它。

const char *myException::CantOpen::what() const { return "Can't Open File For Encryption"; }

你们都帮了大忙

谢谢

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-03
    • 2019-01-02
    • 2014-11-22
    • 2014-10-08
    • 2011-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多