我是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