简体   繁体   中英

C++ code working in VS2010 but not in 2013

I have a pecular problem. Code in my application working without any problem in VS2010 and when I today migrated it to VS2013, it is throwing me an error.

Code is -

#include "stdafx.h"
#include <iostream>

class abc
{
    int value;
public:
    abc() { value = 3;  }
    const int value() const { return ::value(*this); }


    friend const int value(const abc& var){ return var.value; }
};

int _tmain(int argc, _TCHAR* argv[])
{
    abc obj;
    std::cout<<obj.value();
    return 0;
}

It is throwing below errors-

Error   1   error C3861: 'value': identifier not found  c:\consoleapplication1\consoleapplication1\consoleapplication1.cpp  13  1   ConsoleApplication1
    2   IntelliSense: function "value" cannot be called with the given argument list
            argument types are: (const ABC) c:\ConsoleApplication1\ConsoleApplication1\ConsoleApplication1.cpp  13  35  ConsoleApplication1

I search a lot on StackOverFlow and on Google with no luck.

I'm very surprised this compiled on VS2010. Unless stdafx.h contained a function definition/declaration for value , you're calling a function that has not been defined within abc::value() .

Also, abc contains both a data member and a member function named value , which is not allowed. To fix the errors, rename the data member value to something else (I've chosen to name it value_ ).

Then, provide a declaration of the friend function before the definition of abc . I've also gotten rid of the top-level const s on the function return types.

class abc;
int value(const abc& var);

class abc
{
    int value_;
public:
    abc() { value_ = 3;  }
    int value() const { return ::value(*this); }

    friend int value(const abc& var){ return var.value_; }
};

Live demo


Another option, one that I prefer myself, would be to rename the inline friend to something other than value() , and then call it unqualified.

class abc
{
    int value_;
public:
    abc() { value_ = 3;  }
    int value() const { return value_fr(*this); }

    friend int value_fr(const abc& var){ return var.value_; }
};

Live demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM