【发布时间】:2015-05-16 23:41:08
【问题描述】:
尝试对 std::string 进行参数化,以便它支持方法“bool operator==(int)”。我遇到了错误:
$ g++ -std=c++11 te2.cc
te2.cc: In function ‘int main(int, char**)’:
te2.cc:20:20: error: no matching function for call to ‘mstring::mstring(const char [4])’
te2.cc:20:20: note: candidates are:
te2.cc:10:7: note: mstring::mstring()
te2.cc:10:7: note: candidate expects 0 arguments, 1 provided
te2.cc:10:7: note: mstring::mstring(const mstring&)
te2.cc:10:7: note: no known conversion for argument 1 from ‘const char [4]’ to ‘const mstring&’
te2.cc:10:7: note: mstring::mstring(mstring&&)
te2.cc:10:7: note: no known conversion for argument 1 from ‘const char [4]’ to ‘mstring&&’
这里是简单的来源:
#include <unordered_map>
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <iostream>
using namespace std;
class mstring : public string {
public:
//mstring (char* p) : std::string(p) {};
bool operator == (int x) {
int n = atoi(this->c_str());
return (n == x);
}
};
int main(int argc, char *argv[])
{
mstring t("123");
if (t == atoi(argv[1])) {
printf("yes\n");
} else {
printf("no\n");
}
}
如果我取消注释构造函数/mstring (char* p) : std::string(p) {};,那么它编译并运行良好。
问题是,如果可以在不为 mstring 定义构造函数的情况下使其工作,只需使用基类的构造函数(反正没有新的数据成员)?谢谢。
【问题讨论】:
-
通常从
std命名空间继承类是一个非常糟糕的主意。 -
如果您愿意,可以将
operator==(const std::string&, int)定义为独立的非成员函数。事实上,您可能想要这样 - 您可能还想要一个对称的operator==(int, const std::string&),它无论如何都不能是成员函数。 -
您不需要将 argv[1] 转换为 int。直接将其与 std::string 进行比较。