模板類的構造函式呼叫錯誤問題分析

2021-08-02 11:38:12 字數 1648 閱讀 1783

將當時錯誤的**進行簡化後,**如下:

#include #include using namespace std;

templateclass test

void print()

private:

string m_name;

t a;

};class student

testtest("name");

};int main(int argc, char ** argv)

**1

以上**暫且稱為**1.

直接貼上當時提示的錯誤資訊為:

test.cpp:25: 錯誤:expected identifier before string constant

test.cpp:25: 錯誤:expected 『,』 or 『...』 before string constant

乙個模板類,想要初始構建的時候,傳個引數進行,想到的當然是使用建構函式將name進行傳過去。而另乙個類student中使用了test模板類。並在使用過程中,這樣傳入testtest("name"),報出上述錯誤,當時一臉茫然,不知所措。

遇到問題,第一時間自己上網查了下資料,並自己再寫了個小示例,檢視這樣驗證是否ok,**如下:

#include #include using namespace std;

templateclass test

void print()

private:

string m_name;

t a;

};int main(int argc, char ** argv)

**2

以上**稱為**2,大家可以自己試一下,使用g++可以成功通過編繹生成可執行檔案。問題來了,為什麼**1中使用testtest("name")錯誤,而**2中卻沒有問題呢?

解析:自己對於一些基礎概念沒有理解到位

1、**1中,student中使用test的時候,是屬於類成員宣告。宣告階段,只是告訴編繹器,student類中會有testtest這個類成員,並沒有進行記憶體分配,那怎麼可能進行建構函式的呼叫?

2、**2中,main函式中使用testtest,表示的是類的定義。定義指的是真正為類的物件分配記憶體,並構建物件,故這裡使用testtest("name")沒有問題。

3、如果**1中,student類需要使用testtest並在構建的時候將引數傳進去得如何修改?可以在student自身構建的時候,將test的構建函式引數傳進去。具體修改見下面**3部分。

#include #include using namespace std;

templateclass test

void print()

private:

string m_name;

t a;

};class student

testtest;

};int main(int argc, char ** argv)

總結:這個問題暴露自己在基礎概念的理解上還存在不足。一言以蔽之,就是「宣告」與「定義」的理解沒有到位。另外,就是這樣使用的場景用得少,之前沒有用過,多實踐,多發現問題,解決問題,才是成長之道。

c 呼叫基類的建構函式(模板類)

如下 include include include using namespace std template class base template base base t n template void base tostring template derive derive t n base ...

C 學習筆記 非靜態成員函式的非法呼叫錯誤

今天寫程式發現出現非靜態成員的非法呼叫錯誤 原來原因是 1 靜態成員函式相當於全域性函式,只有乙個類名字空間的限制。靜態成員函式是類的函式,無需指明是某個例項物件在操作,既可以是類在呼叫其靜態成員函式也可以是其實例物件來呼叫。注 靜態成員函式只能訪問靜態成員變數和靜態成員函式。2 類成員函式式成員內...

如何呼叫父類的建構函式?

如果想要在子類的建構函式中呼叫父類的建構函式該怎麼辦呢?呼叫父類建構函式的唯一方法是呼叫supper 它看起來會像下面這樣 public class duck extends animal 小孩能夠在父母之前出生嗎?如果你把父類想象成子類的父母,那就可以看出來誰是先存在的。父類的部分必須在子類建立完...