c++ - 调用外部访问器函数时出错

标签 c++ visual-studio

<分区>

如果我有课

Class A 
{
    public:
        UINT getfoo ();

... other stuff ...

    private:
        UINT initfoo (data);
        UINT foo;

     ... other stuff ...
}

我的想法是,在类构造函数中,我设置了

foo = initfoo (data);

getfoo 是一个简单的返回语句

UNIT getfoo ()
{
     return foo;
}

然后从一个外部函数,其中我有那个类的一个实例,我使用 getfoo 访问器函数来获取那个类中 foo 的值。

 A    a;
 UINT myfoo;
 ...
 myfoo = A::getfoo
 -or-
 myfoo = a.getfoo

但是当我尝试在外部函数中分配相同类型的值时,我不断收到错误。

使用 A::VS2013 在编辑器中出现错误

A value of type UINT (A::*)() cannot be assigned to an entity of type UINT

使用一个。编辑器没有提示,但是当我尝试编译时出现错误:

error C2440: '=' : cannot convert from 'unsigned int (__thiscall A::*)(void)' to 'unsigned int'

我确定这是一个基本的 C++ 问题,我已经搜索了很多,但我似乎无法找到正确的搜索词来解决我的问题。我在函数调用中做错了什么?

最佳答案

你的函数调用应该是这样的:

myfoo = a.getfoo();

另外,一个mutator返回一个值是不正常的,所以

UINT initfoo (data);

应该是

void initfoo (data);

此外,坚持访问器/修改器的以下命名约定也是一种很好的做法:

UINT foo;
UINT getFoo();
void setFoo(UINT val);

EDIT const 示例:

class A
{
public:

  // Initialise foo to some random number
  A()
    : foo(4U)
  {
    // constructor body here
  }

private:
  // Once initialised foo cannot change during the lifetime of this object
  const UINT foo;
};

为了清晰起见,我将声明和实现放在一起。如果将其拆分为 .h/.cpp,则初始化器列表与构造函数定义一起进入 .cpp

关于c++ - 调用外部访问器函数时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36041708/

相关文章:

c++ - avghookx.dll 找不到或打开 PDB 文件

c++ - Visual Studio 2010 SP1 中的 64 位整数初始化错误

c++ - 为什么 MinGW 会自动包含 <windef.h>

visual-studio - 与解决方案团队共享reshaper和stylecop设置

c++, protected 抽象虚拟基纯虚拟私有(private)析构函数

c++ - 如何在 Qt 的默认用户浏览器中打开链接?

visual-studio - 为什么 AutoCAD 插件依赖于特定的 Visual Studio 版本?

c# - Visual Studio 调试 "quick watch"工具和 lambda 表达式

c++ - 如何在特定窗口中设置控件的初始焦点?

c++ - 将一段文本读入字符串 vector