我是C ++的新手,我遇到这样的错误:
行为:在以下位置上内存操作不当或内存泄漏: MyInteger :: isPrime(int)(MyInteger.cpp:72)通过:main(main.cpp:23)
在:MyInteger :: isPrime(int)(MyInteger.cpp:59)
那是什么意思,我该如何解决?我尝试使用valgrind
,但对于新生来说似乎有点复杂。
//MyInteger.cpp
bool MyInteger::isPrime(int z){
int i,flag1;
if(z == 1){
flag1 = 1;
}
for(i = 2; i < z; i++){
if(z % i == 0)
{
flag1 = 1;
break;
}else flag1 = 0;
}
if(flag1 == 1){
return false;
}else return true;
}
//MyInteger.hpp
class MyInteger{
public:
static bool isPrime(int);
};
//main.cpp
int main{
const string words[3][2] = {"not even", "even",
"not odd", "odd",
"not prime", "prime"};
..............................
..............................
...............................
cout << "Integer " << b << " is: ";
cout << words[0][MyInteger::isEven(b)] << ", ";
cout << words[1][MyInteger::isOdd(b)] << ", ";
cout << words[2][MyInteger::isPrime(b)] << ".\n";
}
答案 0 :(得分:0)
似乎您的函数isPrime
是私有函数,无法在main()中调用
这段代码对我有用
// Example program
#include <iostream>
#include <string>
using namespace std;
class MyInteger
{
public: static bool isPrime(int);
};
bool MyInteger::isPrime(int z)
{
int i,flag1;
if(z == 1){
flag1 = 1;
}
for(i = 2; i < z; i++){
if(z % i == 0)
{
flag1 = 1;
break;
}else flag1 = 0;
}
if(flag1 == 1){
return false;
}else return true;
}
int main()
{
const string words[3][2] = {"not even", "even",
"not odd", "odd",
"not prime", "prime"};
int b=2;
cout << "Integer " << b << " is: ";
cout << words[2][MyInteger::isPrime(b)] << ".\n";
}
输出
Integer 2 is: not prime.