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

C++实例化Word类遇‘no matching function for call to Word::Word()’错误求助

问题解决:no matching function for call to 'Word::Word()'

错误原因

当类中定义了自定义构造函数(如你的Word(string w)),C++编译器不会自动生成无参默认构造函数Word()。而代码中Word Palindrome;这行试图调用这个不存在的无参构造函数,因此触发报错。

修复步骤

  1. 补充无参构造函数
    在Word类中添加无参构造函数,让对象可以被默认初始化:
class Word{
    public: 
        int length;
        string word;
        void TestForPalindrome();
        // 添加无参构造函数
        Word() {}
        Word(string w){
            word = w;
            length = word.length();
        }
};
  1. 修正其他代码问题
    除了构造函数的问题,代码还有几处逻辑错误需要调整:
  • 回文判断的循环条件错误:原for(int i = length; i < 0; i--)永远不会执行,应改为for(int i = length - 1; i >= 0; i--)(字符串索引从0开始,最后一个字符下标为length-1)。
  • GetInput函数直接修改对象成员不符合封装原则,建议添加setter方法。
  • main函数未调用GetInput(),程序无法执行输入和判断逻辑。

完整修正代码

#include <iostream>
#include <string>

using namespace std;

class Word{
    public: 
        int length;
        string word;
        void TestForPalindrome();
        // 无参构造函数
        Word() {}
        Word(string w){
            word = w;
            length = word.length();
        }
        // 设置单词的setter方法
        void setWord(string w){
            word = w;
            length = word.length();
        }
};

void Word::TestForPalindrome(){
    string testWord;
    // 修正循环逻辑
    for(int i = length - 1; i >= 0; i--){
        testWord += word[i];
    }
    if (testWord == word){
        cout << word << " is a palindrome!" << endl;
    } else {
        cout << word << " is not a palindrome" << endl;
    }
}

void GetInput(Word& palindrome){
    cout << "enter a word: \n";
    string input;
    cin >> input;
    palindrome.setWord(input);
    palindrome.TestForPalindrome();
}

int main(){
    Word Palindrome;
    GetInput(Palindrome);
    return 0;
}

内容的提问来源于stack exchange,提问作者Ivan Sepulveda

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 09:55:15