第 1 点
const char* IllegalArgumentException::what() { return s.c_str(); }
如果在class 或struct 中声明,则声明不正确。由于声明是在 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 建议完全不要使用析构函数。编译器将为您创建它。不用写就别写,因为不存在的代码没有bug。
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。谨慎使用。