Reputation: 13
This is my process.cpp
#include<iostream>
#include "process.h"
#include "CString.h"
void process(const char* s){
w1::Cstring cs(s);
std::cout << cs;
}
My 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
And this is my 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;
}
}
I am getting an error which says that I dont have any matching constructor for initialisation of w1::CString in process.cpp I dont know how to correct it.
Upvotes: 0
Views: 52
Reputation: 4873
I would recommend changing the parameter type of the constructor to const char *
instead, if the constructor does not modify the parameter, as in your code. Compilers are allowed to implicitly convert non-const
to const
, but not the other way around, as your code shows.
Upvotes: 1
Reputation: 8171
You wrote your constructor Cstring(char* s);
as taking a non-const pointer. But your function void process(const char* s)
is trying to pass it a const pointer. The compiler won't automatically cast away constness (and for good reason).
However since that constructor doesn't seem to be modifying its parameter, you should change it to a const pointer:
Cstring(const char* s);
And thus that error will be solved.
Upvotes: 4