我正在尝试编写自己的字符串类(出于理解目的)。我写的如下,文件1 string.h
#include<iostream>
#include<string.h>
namespace MyString
{
class string
{
char* ch;
int len;
public:
string();
string(const char* ch);
char* getString();
int length();
};
}
文件 2 字符串.cpp
#include<iostream>
#include"string.h"
using namespace std;
using MyString::string; // use string from MyString namespace only.
string::string()
{
ch = NULL;
len = 0;
}
string::string(const char* ch)
{
this->ch = ch;
}
char* string::getString()
{
return ch;
}
int string::length()
{
return len;
}
int main()
{
string obj = "This is a test";
cout << obj.getstring<<endl;
return 0;
}
但是我的程序甚至无法编译,出现以下错误
g++ string.cpp -o string
string.cpp:6:1: error: reference to ‘string’ is ambiguous
string.h:5:8: error: candidates are: class MyString::string
/usr/include/c++/4.6/bits/stringfwd.h:65:33: error: typedef struct std::basic_string<char> std::string
string.cpp:6:1: error: ‘string’ does not name a type
string.cpp:12:1: error: reference to ‘string’ is ambiguous
string.h:5:8: error: candidates are: class MyString::string
/usr/include/c++/4.6/bits/stringfwd.h:65:33: error: typedef struct std::basic_string<char> std::string
string.cpp:12:1: error: ‘string’ does not name a type
string.cpp:23:7: error: reference to ‘string’ is ambiguous
string.h:5:8: error: candidates are: class MyString::string
/usr/include/c++/4.6/bits/stringfwd.h:65:33: error: typedef struct std::basic_string<char> std::string
string.cpp:23:7: error: reference to ‘string’ is ambiguous
string.h:5:8: error: candidates are: class MyString::string
/usr/include/c++/4.6/bits/stringfwd.h:65:33: error: typedef struct std::basic_string<char> std::string
string.cpp: In function ‘char* getString()’:
string.cpp:25:9: error: ‘ch’ was not declared in this scope
string.cpp: At global scope:
string.cpp:28:5: error: reference to ‘string’ is ambiguous
string.h:5:8: error: candidates are: class MyString::string
/usr/include/c++/4.6/bits/stringfwd.h:65:33: error: typedef struct std::basic_string<char> std::string
string.cpp:28:5: error: reference to ‘string’ is ambiguous
string.h:5:8: error: candidates are: class MyString::string
/usr/include/c++/4.6/bits/stringfwd.h:65:33: error: typedef struct std::basic_string<char> std::string
string.cpp: In function ‘int length()’:
string.cpp:30:9: error: ‘len’ was not declared in this scope
string.cpp: In function ‘int main()’:
string.cpp:35:2: error: reference to ‘string’ is ambiguous
string.h:5:8: error: candidates are: class MyString::string
/usr/include/c++/4.6/bits/stringfwd.h:65:33: error: typedef struct std::basic_string<char> std::string
string.cpp:35:9: error: expected ‘;’ before ‘obj’
make: *** [string] Error 1
我没有得到共鸣,为什么编译器使用 MyNamespace 中的字符串显式给出错误(即使用 MyNamespace::string;)?
在这方面的任何指示都会非常有帮助。