C++构造函数匹配错误:无匹配AMA::Product构造函数实例
Hey there, let's work through this constructor error you're hitting! Let's start by breaking down why the error is happening, then cover straightforward fixes that fit your assignment requirements.
Why You're Seeing the Error
Your test code has this line:
MyProduct::MyProduct() : Product("", "", "") {}
This is trying to call a Product constructor that takes three const char* arguments—but you only implemented two constructors for the Product class:
- A 0-1 parameter constructor (I assume this has a default value for
type, making it usable with 0 arguments, as noted in your assignment requirement) - A 7-parameter constructor with the signature
Product(const char* sku, const char* address, const char * unit, int onHand, int needed, double beforeTax, bool taxable);
Since there's no 3-parameter constructor defined, the compiler can't find a matching overload, hence the error message: 不存在与参数列表匹配的AMA::Product::Product构造函数实例。
Fixes That Fit Your Assignment Rules
1. Update the Test Code to Use Your Existing Constructors
This is the most direct fix that strictly follows your assignment's requirement to only implement those two constructors. You have two options here:
- If your 1-parameter constructor has a default value (e.g., declared as
Product(char type = '\0');), use the 0-parameter form:MyProduct::MyProduct() : Product() {} - Or, use your 7-parameter constructor by providing reasonable default values for the missing 4 parameters:
MyProduct::MyProduct() : Product("", "", "", 0, 0, 0.0, false) {}
Either of these will let the compiler find a matching constructor and resolve the error.
2. Add a Delegating Constructor (If Test Code Can't Be Modified)
If you can't change the professor's provided test code, you can add a 3-parameter constructor that delegates to your existing 7-parameter one. This doesn't add new logic—it just forwards the arguments and fills in default values for the rest. Here's how:
// Add this to your Product class definition Product(const char* sku, const char* address, const char* unit) : Product(sku, address, unit, 0, 0, 0.0, false) {}
This constructor acts as a thin wrapper for your 7-parameter one, so it doesn't violate the spirit of your assignment (you're still relying on the core constructors you were asked to implement). Just make sure to check with your professor if this is allowed, to be safe.
内容的提问来源于stack exchange,提问作者Lean Junio

