在index.hpp中,我创建了一个具有多个数据成员的类,如int age
、std::string city;
等。我在类外部定义了一个构造函数。在program.cpp中,我创建了一个名为SAM的对象。当我试图编译它时,它显示错误。什么原因?
Program.cpp
#include<iostream>
#include "index.hpp"
int main(){
profile sam("Sam Drakkila", 30, "New York", "USA", "he/him");
std::cout<<sam.name;
}
index.hpp
#include<iostream>
#include<vector>
class profile{
public:
std::string name;
int age;
std::string city;
std::string country;
std::string pronouns;
std::vector<std::string> hobbies;
};
profile::profile(std::string new_name, int new_age,std::string
new_city,std::string new_country, std::string
new_pronouns = "they/them"){
name = new_name;
age = new_age;
city = new_city;
country = new_country;
pronouns = new_pronouns;
}
错误信息
In file included from program.cpp:2:0:
index.hpp:15:1: error: prototype for 'profile::profile(std::__cxx11::string, int, std::__cxx11::string, std::__cxx11::string, std::__cxx11::string)' does not match any in class 'profile'
profile::profile(std::string new_name, int new_age,std::string
^~~~~~~
index.hpp:4:7: error: candidates are: profile::profile(profile&&)
class profile{
^~~~~~~
index.hpp:4:7: error: profile::profile(const profile&)
index.hpp:4:7: error: profile::profile()
program.cpp: In function 'int main()':
program.cpp:5:62: error: no matching function for call to 'profile::profile(const char [13], int, const char [9], const char [4], const char [7])'
profile sam("Sam Drakkila", 30, "New York", "USA", "he/him");
^
In file included from program.cpp:2:0:
index.hpp:4:7: note: candidate: profile::profile()
class profile{
^~~~~~~
index.hpp:4:7: note: candidate expects 0 arguments, 5 provided
index.hpp:4:7: note: candidate: profile::profile(const profile&)
index.hpp:4:7: note: candidate expects 1 argument, 5 provided
index.hpp:4:7: note: candidate: profile::profile(profile&&)
index.hpp:4:7: note: candidate: profile::profile(const profile&)
index.hpp:4:7: note: candidate expects 1 argument, 5 provided
index.hpp:4:7: note: candidate: profile::profile(profile&&)
index.hpp:4:7: note: candidate expects 1 argument, 5 provided
.\index }
index.hpp:15:1: error: prototype for 'profile::profile(std::__cxx11::string, int, std::__cxx11::string, std::__cxx11::string, std::__cxx11::string)' does not match any in class 'profile'
profile::profile(std::string new_name, int new_age,std::string
^~~~~~~
index.hpp:4:7: error: candidates are: profile::profile(profile&&)
class profile{
^~~~~~~
index.hpp:4:7: error: profile::profile(const profile&)
index.hpp:4:7: error: profile::profile()
我在类外定义了一个构造函数
是的,但您没有在类中声明它。
此外,除非您正在创建模板,否则不应该将代码放在头文件中。
要解决问题,请将声明添加到类中:
class profile{
public:
profile(std::string new_name, int new_age, std::string new_city, std::string new_country, std::string new_pronouns);
std::string name;
int age;
std::string city;
std::string country;
std::string pronouns;
std::vector<std::string> hobbies;
};
您还应该考虑将构造函数的代码移动到index.cpp,并为清楚起见重命名文件profile.hpp和profile.cpp。