c++ - 为什么我看到 “member function with the same name as its class must be a constructor”?

标签 c++ constructor compiler-errors

我有一个有用的功能,希望将其从独立的实用程序转换为RAII风格的帮助程序类。在粘贴函数代码并将其重命名之前,我对类的定义一直很好。这时,函数名称用红色下划线标出,并且工具提示显示“与类相同名称的成员函数必须是构造函数”。
此错误消息没有帮助。我知道,我无法编写与该类同名的函数。我希望这个函数成为构造函数。为什么不呢这是怎么回事?
之前:

void Useful( int Param ) // works, and is useful
{
    // do useful things
}
后:
class Useful
{
    void Useful( int Param ) // generates error
    {
        // do useful things
    }
};

最佳答案

问题是剪切和粘贴错误。返回类型的存在阻止了将函数解释为构造函数。

所以:

class Useful
{
    Useful( int Param ) // problem solved
    {
        // do useful things
    }
};

关于c++ - 为什么我看到 “member function with the same name as its class must be a constructor”?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54335465/

相关文章:

c++ - 递归程序不适用于大输入

mysql - ErrorException (E_ERROR) undefined variable : buildingSections

sdl - 使用SDL_Surface的外部编译错误

无法使用 MinGW 编译之前修改的 Nethack - 缓存问题?

c++ - boost UTF-16 字符串的库?

c++ - 在 C++ 中定义复数常量 "i"(#define 与 const)

c++ - BigInteger:在 C++ 中使用 ofstream 写入文件时将基数更改为 2 的方法?

java - 实例化第二个类,java会等到第二个类的构造函数完成,然后移动到下一行代码吗?

design-patterns - 什么时候使用工厂模式而不是重载的构造函数来实例化对象更有意义?

c++ - 类在多个文件上的使用 .h .cpp main.cpp