我是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;
}
第三个参数是一个int,“9999”不是int,也可以转换为一个。 – Borgleader 2014-10-27 20:20:02
错误很明显。你给它一个数组,它需要一个'int'。顺便说一句,摆脱那个指针,只是做'TestClass a(...);'你也可以摆脱'this->'无处不在,以及包含后面的分号。 – chris 2014-10-27 20:20:27
顺便说一句:如果你分配一个对象,你也应该释放它。为了避免错误,请使用智能指针,例如'std :: unique_ptr'。更好:将它放在堆栈上,并避免堆堆在一起。你也可以看一下ctor-init-lists,并搜索“避免使用命名空间标准;'”。 – Deduplicator 2014-10-27 20:28:51