The problem of coincidence of parameter names and member variable names of member functions in C + +

Source: Internet
Author: User

One day when writing classes suddenly thought of this problem, the following to explain how to solve the problem.

Define a class:

class test{public:    void  setnum ();     void getnum (); Private :     int num;}; void Test::setnum () {    ten;} void Test::getnum () {    printf ("%d\n", num);}

Run:

int Main () {        test one;       One.setnum ();       One.getnum ();           return 0 ;}

Console output 100, which indicates that member functions can be directly modified by the member variables without relying on parameter arguments .

Next we can make a change to the member function of the assignment:

#include <stdio.h>#include<windows.h>#include<mysql.h>classtest{ Public:    voidSetnum (intx); voidgetnum ();Private:    intnum;};voidTest::setnum (intx) {num=x;}voidTest::getnum () {printf ("%d\n", num);}intMain () {test one; One.setnum ( -);          One.getnum (); return 0;}

Console output 100

Let's make another change:

class test{public:    void setnum (int  num);     void getnum (); Private :     int num;}; void test::setnum (int  num) {    = num;}

At this point in the run, the member function that found the assignment is not running at all.

The solution is:

void test::setnum (int  num) {    this->num = num;} 

Use this pointer to distinguish between the two variables.

The problem of coincidence of parameter names and member variable names of member functions in C + +

Related Article

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.