一、判断完美数(真因子之和等于自身)
二、代码实现
#include<iostream>
#include<thread>
#include<stdlib.h>
class ThreadGuard{
public:
ThreadGuard(std::thread t):t_(std::move(t)){}
~ThreadGuard(){
if(t_.joinable()){ //判断是否可以成功使用join()或者detach(),返回true表示可以使用join()或者detach()返回fasle表示不可以
t_.join(); //等待这个线程执行完毕
}
}
ThreadGuard(ThreadGuard&)=delete;
ThreadGuard operator =(ThreadGuard&)=delete;
private:
std::thread t_;
};
class Perfect{
public:
Perfect(int n):n(n){}
void operator()(){ //operator()()的含义:1、第一个括号代表我要重载运算符() 2、第二个括号代表重载时传入的参数,可以有参数,也可以不传入参数
if(factorSum(n) == n){
std::cout<<"yes\n";
}else{
std::cout<<"no\n";
}
}
private:
int factorSum(const int n){
int total=0;
for(int i=1;i<n;i++){
if(n%i==0) total+=i;
}
return total;
}
int n;
};
int main(int argc,char*argv[]){
int n=atoi(argv[1]);
Perfect pf(n);
std::thread t(pf); //创建线程,线程起点是pf
ThreadGuard tg(std::move(t)); //从主线程中分离开
return 0;
}
三、结果演示
![](https://img-blog.csdnimg.cn/ca226a652b4e480c922e06a9be465838.png)