2014-10-27 43 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

相關問題