因此,对于类,我们正在学习C ++中的OOP,并且我构建了我的类,但每次我尝试编译它时都会收到此错误消息:
Undefined symbols for architecture x86_64:
"Player::set_assits(int)", referenced from:
_main in playerDataBase-666bbb.o
"Player::set_last_name(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >)", referenced from:
_main in playerDataBase-666bbb.o
"Player::set_team_name(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >)", referenced from:
_main in playerDataBase-666bbb.o
"Player::set_first_name(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >)", referenced from:
_main in playerDataBase-666bbb.o
"Player::set_year_of_birth(int)", referenced from:
_main in playerDataBase-666bbb.o
"Player::set_goals(int)", referenced from:
_main in playerDataBase-666bbb.o
"Player::Player()", referenced from:
_main in playerDataBase-666bbb.o
"Player::~Player()", referenced from:
_main in playerDataBase-666bbb.o
ld: symbol(s) not found for architecture x86_64
我无法理解为什么会发生这种情况,我试图通过编译单独的.h和.cpp文件以及将类和main函数放在同一个.cpp文件中来运行它。任何帮助将不胜感激,这里是我的代码。
#include <iostream>
#include <string>
using namespace std;
class Player{
public:
Player();
~Player();
// accessors and mutators
void set_first_name(string in_first_name);
string first_name();
void set_last_name(string in_last_name);
string last_name();
void set_team_name(string in_team_name);
string team_name();
void set_year_of_birth(int in_year_of_birth);
int year_of_birth;
void set_goals(int in_goals);
int goals;
void set_assits(int in_assists);
int assists;
//methods
void display();
private:
string first_name_;
string last_name_;
string team_name_;
int year_of_birth_;
int goals_;
int assits_;
};
void Player::display(){
cout << first_name_ << last_name_ << endl;
}
int main(){
Player player;
player.set_first_name("John");
player.set_last_name("Tedesco");
player.set_team_name("Blyth Warriors");
player.set_year_of_birth(2002);
player.set_goals(2);
player.set_assits(7);
player.display();
}
感谢您的任何帮助,并再次抱歉凌乱/糟糕的代码。
谢谢,
约翰
答案 0 :(得分:2)
这些方法都没有定义,只是声明了:
Player();
~Player();
// accessors and mutators
void set_first_name(string in_first_name);
string first_name();
void set_last_name(string in_last_name);
string last_name();
void set_team_name(string in_team_name);
string team_name();
void set_year_of_birth(int in_year_of_birth);
void set_goals(int in_goals);
void set_assits(int in_assists);
您需要为这些方法提供合理的定义。现在,您告诉编译器您将为每个方法提供一个定义,而且永远不会。对于默认构造函数,如果希望编译器生成构造函数,则可以使用Player() = default;
。
例如,要定义first_name
属性,您可以执行以下操作:
void Player::set_first_name(const string& in_first_name)
{
first_name_ = in_first_name;
}
const string& first_name() const
{
return first_name_;
}
请注意我已将此更改为通过常量引用获取值,并且出于效率原因,通过常量引用而不是值返回值。
答案 1 :(得分:-1)
你宣布了所有那些花哨的方法,例如:
void set_first_name(string in_first_name);
string first_name();
但你从未定义过它们!
实施它们,它会起作用,例如:
void set_first_name(string in_first_name) {
first_name_ = in_first_name;
}
string first_name() {
return first_name_;
}