头文件ex10.h
#include <string>
class MyInteger{
public:
MyInteger();
MyInteger(int);
int getValue() const;
bool isEven() const;
bool isOdd() const;
bool isPrime() const;
static bool isEven(int);
static bool isOdd(int);
static bool isPrime(int);
static bool isEven(const MyInteger&);
static bool isOdd(const MyInteger&);
static bool isPrime(const MyInteger&);
bool equals(int) const;
bool equals(const MyInteger&) const;
static int parseInt(const std::string&);
private:
int value;
};#include <string>
class MyInteger{
public:
MyInteger();
MyInteger(int);
int getValue() const;
bool isEven() const;
bool isOdd() const;
bool isPrime() const;
static bool isEven(int);
static bool isOdd(int);
static bool isPrime(int);
static bool isEven(const MyInteger&);
static bool isOdd(const MyInteger&);
static bool isPrime(const MyInteger&);
bool equals(int) const;
bool equals(const MyInteger&) const;
static int parseInt(const std::string&);
private:
int value;
};
类的实现文件ex10.cp
#include "ex10.h"
#include <string>
#include <cstdlib>
MyInteger::MyInteger(){
//nothing
}
MyInteger::MyInteger(int value){
this->value = value;
}
int MyInteger::getValue() const{
return value;
}
bool MyInteger::isEven() const{
return isEven(value);
}
bool MyInteger::isOdd() const{
return isOdd(value);
}
bool MyInteger::isPrime() const{
return isPrime(value);
}
bool MyInteger::isEven(int newValue){
return (newValue % 2) == 0;
}
bool MyInteger::isOdd(int newValue){
return (newValue % 2) != 0;
}
bool MyInteger::isPrime(int newValue){
if(newValue < 2)
return false;
for(int i = 2; i <= newValue / 2; ++i)
if(newValue % i == 0)
return false;
return true;
}
bool MyInteger::isEven(const MyInteger &obj){
return isEven(obj.getValue());
}
bool MyInteger::isOdd(const MyInteger &obj){
return isOdd(obj.getValue());
}
bool MyInteger::isPrime(const MyInteger &obj){
return isPrime(obj.getValue());
}
bool MyInteger::equals(int newValue) const{
return value == newValue;
}
bool MyInteger::equals(const MyInteger &obj) const{
return value == obj.getValue();
}
int MyInteger::parseInt(const std::string &s){
return atoi(s.c_str()); //使用atoi函数前把字符串转化为C风格
}
测试文件main.cpp
#include <iostream>
#include "ex10.h"
using namespace std;
int main(){
MyInteger mi(5);
cout << "mi.getValue() = " << mi.getValue() << endl;
cout << "mi.isEven() = " << mi.isEven() << endl;
cout << "mi.isPrime() = " << mi.isPrime() << endl;
cout << "11 is Prime? " << MyInteger::isPrime(11) << endl;
cout << "isEven(mi) = " << MyInteger::isEven(mi) << endl;
return 0;
}