I put all codes in main.cpp, it run successfully. However, I separated them into different header file and cpp files, there was a error message: 2 duplicate symbols for architecture x86_64. I suppose I made mistakes in marcos.
//CString.h
#ifndef _CSTRING_H_
#define _CSTRING_H_
#include<iostream>
namespace w1{
extern const int MAX = 3;
class CString{
char* _s;
public:
CString(const char *);
void display(std::ostream&) const;
~CString(){if (_s != nullptr) delete [] _s;}
};
std::ostream& operator<<(std::ostream&, CString&);
}
#endif
//CString.cpp
#include"CString.h"
namespace w1{
CString::CString(const char* s){
if (s != nullptr){
_s = new char [MAX];
for(int i = 0; i < MAX; i++)
_s[i] = s[i];
}
else
_s = nullptr;
}
void CString::display(std::ostream& os) const{
if(_s != nullptr)
os << _s << std::endl;
else
os << "The string is empty." << std::endl;
}
std::ostream& operator<<(std::ostream& os, CString& target) {
target.display(os);
return os;
}
}
//main.cpp
#include"CString.h"
using namespace w1;
void process(const char* );
void process( const char* s){
w1::CString instance(s);
std::cout << instance << std::endl;
}
int main(int argc, char *argv[]){
if (argc == 1)
std::cout << "Insufficient number of arguments (min 1)" << std::endl;
else{
std::cout << "Maximum number of characters stored : " << w1::MAX <<std::endl;
for (int i = 1; i < argc; i++){
std::cout << i << ": ";
process(argv[i]);
}
}
return 0;
}
Aucun commentaire:
Enregistrer un commentaire