點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
你忘記了標題周圍的守衛。 –