gpt4 book ai didi

c++ - 获取构造函数初始化错误

转载 作者:太空宇宙 更新时间:2023-11-04 16:07:43 25 4
gpt4 key购买 nike

这是我的进程.cpp

#include<iostream>
#include "process.h"
#include "CString.h"
void process(const char* s){
w1::Cstring cs(s);
std::cout << cs;
}

我的 CString.h

#ifndef _CSTRING_H
#define _CSTRING_H
#include<iostream>
namespace w1{
const int CHAR_NUM=3;
class Cstring{
public:
char str[CHAR_NUM+1];
Cstring(char* s);
void display(std::ostream& os) const;

};
std::ostream& operator<<(std::ostream&os ,const Cstring& cs);
}
#endif

这是我的 CString.cpp

#include <iostream>
#include "CString.h"
namespace w1{
Cstring::Cstring(char* s){
if (s=='\0'){
str[0]='\0';
}else{
for (int i=0;i<CHAR_NUM;i++){
str[i]=s[i];
str[i+1]='\0';
}
}
}
void Cstring::display(std::ostream& os) const{
os<<str<<std::endl;
}

std::ostream& operator<<(std::ostream&os ,const Cstring& cs){
cs.display(os);
return os;
}
}

我收到一个错误,提示我在 process.cpp 中没有任何匹配的构造函数来初始化 w1::CString我不知道如何纠正它。

最佳答案

您将构造函数 Cstring(char* s); 编写为采用非常量指针。但是您的函数 void process(const char* s) 正试图向它传递一个 const 指针。编译器不会自动放弃常量(并且有充分的理由)。

然而,由于该构造函数似乎没有修改其参数,您应该将其更改为常量指针:

Cstring(const char* s);

因此该错误将得到解决。

关于c++ - 获取构造函数初始化错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32708032/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com