我有一个特殊的问题。我的应用程序中的代码在 VS2010 中运行没有任何问题,当我今天将它迁移到 VS2013 时,它抛出了一个错误。
代码是-
#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;
}
它抛出以下错误-
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
我在 StackOverFlow 和 Google 上搜索了很多,但都没有成功。
最佳答案
我很惊讶这是在 VS2010 上编译的。除非stdafx.h
包含 value
的函数定义/声明,您正在调用一个尚未在 abc::value()
中定义的函数.
此外,abc
包含一个名为 value
的数据成员和成员函数, 这是不允许的。要修复错误,请重命名数据成员 value
到别的东西(我选择将其命名为 value_
)。
然后,提供 friend
的声明abc
定义前的函数.我也摆脱了顶级 const
s 在函数返回类型上。
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_; }
};
另一种选择,我自己更喜欢,是重命名内联 friend
到value()
以外的东西,然后称之为不合格。
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_; }
};
关于C++ 代码在 VS2010 中工作但在 2013 中不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24682746/