1

在阅读了 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' 中找不到重载的成员函数。我已经搜索了该错误,但没有找到解决方法。这段代码有什么问题?

4

3 回答 3

5

您需要声明单参数构造:

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

一旦你这样做,将不再有一个编译器合成的默认构造函数,所以如果你需要一个,你将不得不自己编写。如果explicit您不想从int.

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) {
}
于 2012-08-14T15:52:56.163 回答
2

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

class Player {
public:
    Player( int y );
    string name;
    int level;
};
于 2012-08-14T15:52:46.103 回答
1
class Player 
{ 
public:
 Player(int );    
 string name;
 int level;
 };
于 2012-08-14T15:54:12.607 回答