[英]VS2010 overloaded member function not found
在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'中找不到重載的成員函數。 我已經搜索了錯誤,但沒有找到解決方法。 此代碼有什么問題?
您需要聲明單個參數的構造:
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) {
}
在類中為此構造函數添加聲明。
class Player {
public:
Player( int y );
string name;
int level;
};
class Player
{
public:
Player(int );
string name;
int level;
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.