2014-10-27 72 views
-4

我是C++的新手,并试图只返回通过构造函数传递的值,我不确定我在下面的代码中做了什么错误,它总是给我一个错误:no instance of constructor..matches,cannot convert parameter 3 from 'const char [5]' to 'int'C++错误没有构造函数的实例

#include <iostream> 
#include <string> 
using namespace std; 

class TestClass{ 
    string a; 
    string b; 
    int x; 
public: 
    TestClass(string m, string n, int y){ 
     this->a = m; 
     this->b = n; 
     this->x = y; 
    } 
    int test(){ 
     return this->x; 
    } 
}; 

int main(){ 
    TestClass *a = new TestClass("test1","test2","9999"); 
    cout<<a->test()<<endl; 
} 
+0

第三个参数是一个int,“9999”不是int,也可以转换为一个。 – Borgleader 2014-10-27 20:20:02

+0

错误很明显。你给它一个数组,它需要一个'int'。顺便说一句,摆脱那个指针,只是做'TestClass a(...);'你也可以摆脱'this->'无处不在,以及包含后面的分号。 – chris 2014-10-27 20:20:27

+0

顺便说一句:如果你分配一个对象,你也应该释放它。为了避免错误,请使用智能指针,例如'std :: unique_ptr'。更好:将它放在堆栈上,并避免堆堆在一起。你也可以看一下ctor-init-lists,并搜索“避免使用命名空间标准;'”。 – Deduplicator 2014-10-27 20:28:51

回答

3

您传递数字9999为"9999" - 其周围的引号表示它是一个字符串。简单地通过它作为9999

1

你必须从“9999”你的第三个参数更改为9999的报价说,你把它当作一个字符串的时候,其实构造函数期待一个int

+0

好吧,把它当作一个字符串(概念),而不是'string'(C++类型'std :: string')。字符文字的类型为'const char [n]',它与'std :: string'不同。 – cdhowie 2014-10-27 20:38:21