对于我的C ++入门课程的第二学期,我创建了一个名为Name.h
的课程,其中包含以下信息:
#ifndef NAME_H
#define NAME_H
class Name
{
private:
string firstName;
string lastName;
string middleInitial;
public:
Name();
Name(string, string, string);
void setName(string, string, string);
void setFirstName(string);
void setLastName(string);
void setMiddleInitial(string);
void display() const;
string getFirstName() const {
return firstName;
}
string getLastName() const {
return lastName;
}
string getMiddleInitial() const {
return middleInitial;
}
};
#endif
实施在文件Name.cpp
中提供,如下所示:
#include <iostream>
#include <string>
using namespace std;
#include "Name.h"
Name::Name() {}
Name::Name(string firstName, string lastName, string middleInitial) {
this->firstName = firstName;
this->lastName = lastName;
this->middleInitial = middleInitial;
}
void Name::setName(string firstName, string lastName, string middleInitial) {
this->firstName = firstName;
this->lastName = lastName;
this->middleInitial = middleInitial;
}
void Name::setFirstName(string firstName) {
this->firstName = firstName;
}
void Name::setLastName(string lastName) {
this->lastName = lastName;
}
void Name::setMiddleInitial(string middleInitial) {
this->middleInitial = middleInitial;
}
void Name::display() {
cout << firstName << " " << middleInitial << " " << lastName << endl;
}
最后,我尝试在下面的Name_Main.cpp
文件中测试相应的函数和构造函数实现:
#include <iostream>
#include <string>
using namespace std;
#include "Name.h"
int main() {
string firstName;
string lastName;
string middleInitial;
cout << "Using constructor: " << endl;
cout << "Enter first name: ";
cin >> firstName;
cout << "Enter last name: ";
cin >> lastName;
cout << "Enter middle initial: ";
cin >> middleInitial;
Name name(firstName, lastName, middleInitial);
cout << "Date: ";
name.display();
cout << "Using setName(): " << endl;;
cout << "Enter first name: ";
cin >> firstName;
cout << "Enter last name: ";
cin >> lastName;
cout << "Enter middle initial: ";
cin >> middleInitial;
name.setName(firstName, lastName, middleInitial);
cout << "Date: ";
name.display();
cout << "Using setters: " << endl;
cout << "Enter first name: ";
cin >> firstName;
cout << "Enter last name: ";
cin >> lastName;
cout << "Enter middle initial: ";
cin >> middleInitial;
name.setFirstName(firstName);
name.setLastName(lastName);
name.setMiddleInitial(middleInitial);
cout << "Date: ";
name.display();
return 0;
}
尝试使用Cloud9 IDE在Name_Main.cpp
中测试类函数和构造函数后,我一直收到以下错误:
/tmp/cccNHMnU.o: In function `main':
Name_Main.cpp:(.text+0x126): undefined reference to `Name::Name(std::string, std::string, std::string)'
似乎Name_Main.cpp
找不到Name.h
中的相应方法及其在Name.cpp
中的实现方式。我尝试将所有string
变量类型更改为std::string
中的Name.h
变量类型,并将using namespace std;
和#include <string>
添加到头文件中,改为否无济于事。有谁知道为什么我收到这个错误,或者有解决这个问题的建议?