【问题标题】:VS2010 overloaded member function not foundVS2010 重载成员函数未找到
【发布时间】:2012-08-14 15:51:31
【问题描述】:

在阅读了 C++ 网站上的课程教程后,我学习了以下代码,然后我尝试使用它:

class CVector {
  public:
    int x,y;
    CVector () {};
    CVector (int,int);
    CVector operator + (CVector);
};

CVector::CVector (int a, int b) {
  x = a;
  y = b;
}

之后我编写了以下代码,以便学习高效地编写 C++ 类并编写更简洁的代码:

class Player {
public:
    string name;
    int level;
};

Player::Player(int y) {
    level = y;
}

但是它给了我错误 C2511: 'Player::Player(int)' : 在'Player' 中找不到重载的成员函数。 我已经搜索了该错误,但没有找到解决方法。这段代码有什么问题?

【问题讨论】:

    标签: c++ visual-studio-2010 syntax-error


    【解决方案1】:

    需要声明单参数构造:

    class Player {
    public:
        Player(int y);
        std::string name;
        int level;
    };
    

    一旦你这样做,将不再有编译器合成的默认构造函数,所以如果你需要一个,你必须自己编写。如果您不想从 int 进行隐式转换,还可以考虑创建单参数构造函数 explicit

    class Player {
    public:
        explicit Player(int y); // no implicit conversions from int
        Player() :name(), int() {} // default constructor and implementation
        std::string name;
        int level;
    };
    

    此外,如果可能的话,最好使用构造函数初始化列表而不是在构造函数主体中分配值。关于这个主题有很多 SO 问题,所以我不会在这里详细说明。你会这样做:

    Player::Player(int y) : level(y) {
    }
    

    【讨论】:

    • 感谢您指出。我以为它会声明自己,但我是初学者。谢谢!
    • @ThePlan:C++ 使用分离的编译模型。您的类的用户(通常)不会看到方法的定义,因此他们需要声明成员函数,并且编译器强制在定义之前需要声明以避免混淆
    • 感谢您的解释 +1,我是 C++ 的新手,我不知道显式等是如何工作的,但我会尝试应用它并了解更多信息。我接受了这个答案。
    • @ThePlan 很高兴它有帮助。我又添加了一项建议。
    【解决方案2】:

    在你的类中为这个构造函数添加声明。

    class Player {
    public:
        Player( int y );
        string name;
        int level;
    };
    

    【讨论】:

      【解决方案3】:
      class Player 
      { 
      public:
       Player(int );    
       string name;
       int level;
       };
      

      【讨论】:

        猜你喜欢
        • 2016-06-09
        • 2017-09-19
        • 1970-01-01
        • 2021-02-07
        • 2013-03-06
        • 2014-03-06
        • 1970-01-01
        • 2021-12-17
        • 1970-01-01
        相关资源
        最近更新 更多