You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++构造函数调用报错求助(Codecademy课程学习中)

C++构造函数不匹配报错解决

报错信息

profile.cpp:4:1: error: prototype for ‘Profile::Profile(std::__cxx11::string, int, std::__cxx11::string, std::__cxx11::string)’ does not match any in class ‘Profile’
 Profile::Profile(string new_name, int new_age, string new_city, string new_pronouns) {
 ^~~~~~~
In file included from profile.cpp:1:0:
profile.hpp:4:7: error: candidates are: Profile::Profile(Profile&&)
 class Profile {
       ^~~~~~~
profile.hpp:4:7: error:                 Profile::Profile(const Profile&)
profile.hpp:15:5: error:                 Profile::Profile(std::__cxx11::string, int, std::__cxx11::string, std::__cxx11::string, std::__cxx11::string)
     Profile(string new_name, int new_age, string new_city, string new_country, string pronouns);
     ^~~~~~~

问题根源

  1. 类声明(profile.hpp)里的构造函数要求5个参数,但实现(profile.cpp)里只定义了4个,参数数量不匹配,编译器找不到对应原型的函数。
  2. 实现代码里错误使用了未传入的new_country变量,这是参数缺失直接导致的问题。

修正方案

仅修改profile.cpp里的构造函数定义,让它和profile.hpp的声明完全匹配:

修改后的profile.cpp

#include "profile.hpp"
#include <vector>
using namespace std;

Profile::Profile(string new_name, int new_age, string new_city, string new_country, string new_pronouns) {
  name = new_name;
  age = new_age;
  city = new_city;
  country = new_country;
  pronouns = new_pronouns;
}

关键提醒

C++中,类成员函数的声明(头文件)和定义(源文件)必须严格一致,包括参数的数量、类型、顺序,否则编译器会判定为不同的函数,引发匹配错误。

内容的提问来源于stack exchange,提问作者Travis Games

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 20:15:33