我正在编写一个程序,您可以在其中给一个对象一个整数,它可以计算下一个更大的素数。该任务是重载前缀运算符并在构造函数中使用它,以便如果我创建一个对象并将其赋予数字11,则应存储下一个更大的质数(13)。
我的运算符重载看起来像这样:
cPrimZahl& cPrimZahl::operator++()
{
nextprim = prim;
while (!is_Prime(nextprim))
{
++nextprim;
if (nextprim > 10000)
{
while (!is_Prime(nextprim))
{
--nextprim;
}
prim = nextprim;
break;
}
prim = nextprim;
}
cout << "die naechst groessere Primzahl ist: " << prim << endl;
return *this;
}
主要:
int main(){
cPrimZahl obj(13); // The object here is 13 now
++obj1; // Here its 17
return 0;
}
我的构造函数:
cPrimZahl::cPrimZahl(int prim_in)
{
if (prim_in > maxprim) // maxprim = 10000
{
cout << "Prime number is to big! Adjusting..." << endl;
prim = 1;
}
else if (prim_in < 0)
{
cout << "Prime number can't be negative! Adjusting..." << endl;
prim = 1;
}
prim = prim_in;
++prim; // at this point i want it to increment to give me the next bigger prime number
}
我现在尝试了很多方法,但是我总是总是得到规则的增量...运算符重载在构造之前,但是我也试图将构造函数放在重载之前,但都无效。我还能做什么?
答案 0 :(得分:0)
在构造函数中,<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
{% load static %}
<link rel="stylesheet" type="text/css" href="{% static 'blog/style.css' %}">
<title>New Blog post</title>
</head>
<body>
<div class="parallax5" align="center">
<h1 class="a">UPDATE your Blog page</h1><br>
{% if user.has_perm('blog.can_change') %}
<form style="background-color:grey;" method="POST" action=".">
<p>Please only post blogs that are in good taste. You can
update your blog below.</p>
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Update Blog</button>
</form><br>
{% else %}
<p style="background-color:red;color:white;">You do not have permission to update this blog post</p>
{% endif %}
<a style="background-color:white;font-size:50px;" href="{% url 'list' %}">I'm done!<br>Go back to blog list</a>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>
引用了prim
成员(可能是某种整数类型)。因此,prim
使用该整数类型的内置预递增运算符,它将使++prim
成员递增一。
您不想在prim
成员上调用预递增运算符,而是在当前对象本身上调用。
可以使用prim
获取当前对象,因此可以使用*this
来调用预增量运算符。
或者,您可以使用函数调用语法:++(*this);