点1
const char* IllegalArgumentException::what() { return s.c_str(); }
被错误地声明。由于声明是在IllegalArgumentException
类,IllegalArgumentException::
is implied内部编译的,因为编译器现在认为你在声明别的东西。你想
const char* what() { return s.c_str(); }
此外,{ return s.c_str(); }
部分实现的功能,所以没有必要实现它在cpp文件。
点2
在struct
一切public
除非宣布继private
关键字。除非另有说明,否则这与class
相反,其中一切均为private
。一个class
和一个struct
几乎是相同的,除了默认访问的区别。
点3
在C++中,您可以声明区块中成员的访问级别。不需要一次一个地声明成员的访问级别。
struct IllegalArgumentException : public std::exception
{
// these are all public by default in a struct
IllegalArgumentException(std::string ss);
~IllegalArgumentException();
const char* IllegalArgumentException::what() { return s.c_str(); }
private: // everything after this is private
std::string s;
int example;
};
或
class IllegalArgumentException : public std::exception
{
public: // these are all private by default in a class and need to be public
IllegalArgumentException(std::string ss);
~IllegalArgumentException();
const char* IllegalArgumentException::what() { return s.c_str(); }
private: // switch back to private
std::string s;
int example;
};
或
class IllegalArgumentException : public std::exception
{
// these are all private by default in a class
std::string s;
int example;
public: // everything after this is public
IllegalArgumentException(std::string ss);
~IllegalArgumentException();
const char* IllegalArgumentException::what() { return s.c_str(); }
};
4点
IllegalArgumentException::~IllegalArgumentException() {}
没有做任何事情。它不需要做任何事情,所以Rule of Zero建议不要有析构函数。编译器会为你创建它。如果你不必写它,不要写它,因为不存在的代码没有错误。
class IllegalArgumentException : public std::exception
{
// these are all private by default
std::string s;
int example;
public: // everything after this is public
IllegalArgumentException(std::string ss);
const char* IllegalArgumentException::what() { return s.c_str(); }
};
点5
从KerrekSB这里偷窃,因为它是一个点,OP对另外一个问题。 Use Include Guards
包含防护功能可防止在同一translation unit中多次包含标题。这是一个问题,因为膨胀和同一事物被定义或声明的可能性不止一次,导致混淆真实的问题。
一个简单的头文件保护:
#ifndef ILLEGALARGUMENTEXCEPTION_H // if we've never seen ILLEGALARGUMENTEXCEPTION_H
// before, do the following
#define ILLEGALARGUMENTEXCEPTION_H // OK we've seen it now!
// all subsequent includes of IllegalArgumentException.h will have seen
// ILLEGALARGUMENTEXCEPTION_H and fail the ifndef, skipping everything
// until it finds the closing #endif
#include <string>
#include <exception>
class IllegalArgumentException : public std::exception
{
// these are all private by default
std::string s;
int example;
public: // everything after this is public
IllegalArgumentException(std::string ss);
const char* IllegalArgumentException::what() { return s.c_str(); }
};
#endif // end of Include Guard
您也可以使用#pragma once
,但警告说,#pragma
意味着非标准编译器扩展。编译器可能不存在once
,如果不存在,编译器可以不告诉你跳过指令!
once
不在标准中有很多原因,最重要的是它有unresolved fail cases。谨慎使用它。
首先,你的cpp文件中的what()应该是IllegalArgumentException :: what()。 – 0x5453
@ 0x5453,谢谢。修改代码后,只剩下一个错误。 – ssimm
你忘记了标题周围的守卫。 –