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

C++报错:No instance of constructor matches argument list 求助

问题分析与解决方案

核心错误原因

你在main中尝试用两个字符串参数初始化Post对象:

Post post1("Chicken came before the egg confirmed!", "...");

但你的Post类没有定义接受两个std::string参数的构造函数。C++编译器默认只会生成无参的默认构造函数,无法处理带参数的初始化请求,这就是报错的直接原因。

其他需要修复的问题

除了构造函数缺失,代码里还有多处语法不匹配、定义错误的问题,不修复的话即使加了构造函数也无法正常编译:

1. 头文件Post.hpp的问题

  • 所有string类型必须加上std::前缀(你没有使用using namespace std;,必须显式指定命名空间)
  • 类定义的末尾缺少分号;,这是C++类定义的强制要求
  • getTimeStamp()的声明返回int,但实际实现是void,返回值类型不匹配
  • setTimeStamp()声明为无参函数,但实现里带int参数,参数列表不匹配

2. 实现文件Post.cpp的问题

  • 不能重新定义Post类,正确的写法是通过类名::成员函数的方式实现头文件中声明的成员,而不是重复写整个类
  • cout需要加上std::前缀,并且要包含<iostream>头文件
  • displayPost()中直接输出time_t类型的Time会打印原始数值,需要转换为可读的时间格式
  • 成员函数的参数和返回值必须和头文件中的声明严格一致

修正后的完整代码

Post.hpp

#ifndef POST_HPP
#define POST_HPP
#include <string>
#include <ctime>

class Post {
private:
    std::string Title;
    std::string Body;
    time_t Time;
    
public:
    // 新增带标题和内容的构造函数
    Post(const std::string& title, const std::string& body);

    void setTitle(const std::string& title); 
    std::string getTitle(); 

    void setBody(const std::string& body); 
    std::string getBody(); 
     
    void setTimeStamp(); // 设置为当前时间
    void getTimeStamp(); // 打印格式化后的时间
    void displayPost();
}; // 注意这里的分号

#endif

Post.cpp

#include "Post.hpp"
#include <iostream>
#include <cstdio>

// 实现构造函数,初始化标题、内容并设置时间戳
Post::Post(const std::string& title, const std::string& body) 
    : Title(title), Body(body) {
    setTimeStamp();
}

void Post::setTitle(const std::string& title) {
    Title = title;
} 

std::string Post::getTitle() {
    return Title;
}

void Post::setBody(const std::string& body) {
    Body = body;
} 

std::string Post::getBody() {
    return Body;
} 

void Post::setTimeStamp() {
    time(&Time); // 获取当前系统时间
}

void Post::getTimeStamp() {
    struct tm* timestamp = localtime(&Time);
    printf("发布时间: %s", asctime(timestamp));
}

void Post::displayPost() {
    std::cout << Title << " [";
    struct tm* timestamp = localtime(&Time);
    std::cout << asctime(timestamp) << "] : " << Body << std::endl;
}

Main.cpp

(你的main代码无需修改,直接使用即可)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 19:55:16