Four weeks procedure fill in the blanks question 2

Source: Internet
Author: User

4W4: Fourth week procedure fill in the blanks question 2

Description

The following Myint class has only one member variable. Some of the code inside the Myint class is hidden. Suppose the following program can be compiled and the output result is:

4,1

Please write out the hidden parts. (The content you write must be all within the Myint class, and static variables are not allowed in Myint member functions).

#include <iostream>

using namespace Std;

Class MyInt {

int nval;

Public

MyInt (int n) {nval = n;}

int ReturnVal () {return nval;}

Add your code here

};

int main () {

MyInt Objint (10);

Objint-2-1-3;

cout << objint.returnval ();

cout << ",";

objint-2-1;

cout << objint.returnval ();

return 0;

}

input

No

Output

4,1

Sample Input

No

Sample Output

4,1

The idea of solving problems: To change the value of private members within a class, you must use a reference or a pointer. You should add & to your situation before operator. Overloading as a member function means that the number of parameters is the number of operators minus one, namely:

#include <iostream>

using namespace Std;

Class MyInt {

Intnval;

Public

MyInt (INTN) {nval = n;}

Intreturnval () {return nval;}

Add your code here

Myint&operator-(int s)

{

nval-= s;

Return*this;

}

};

int main () {

Myintobjint (10);

ObjInt-2-1-3;

cout<< Objint.returnval ();

cout<< ",";

ObjInt-2-1;

cout<< Objint.returnval ();

Return0;

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.