簡體   English   中英

C++ - 沒有匹配的函數調用

[英]c++ - no matching function for call to

我的終端消息

zo@laptop:~/Desktop$ g++ stack.cpp 
stack.cpp: In function ‘int main(int, char**)’:
stack.cpp:50:19: error: no matching function for call to ‘boyInitial(Boy [boyNumber])’
     boyInitial(boy);
                   ^
stack.cpp:17:6: note: candidate: template<class T, int N> void boyInitial(T (&)[N])
 void boyInitial(T (&boy)[N]){
      ^~~~~~~~~~
stack.cpp:17:6: note:   template argument deduction/substitution failed:
stack.cpp:50:19: note:   variable-sized array type ‘long int’ is not a valid template argument
     boyInitial(boy);
                   ^
stack.cpp:51:19: error: no matching function for call to ‘getBoyAges(Boy [boyNumber])’
     getBoyAges(boy);
                   ^
stack.cpp:34:6: note: candidate: template<class T, int N> void getBoyAges(T (&)[N])
 void getBoyAges(T (&boy)[N]){
      ^~~~~~~~~~
stack.cpp:34:6: note:   template argument deduction/substitution failed:
stack.cpp:51:19: note:   variable-sized array type ‘long int’ is not a valid template argument
     getBoyAges(boy);

我的程序

#include <iostream>

class People{
    public:
        char *name;
        int age;
};

class Boy : public People{
    public:
        void say(void){
            std::cout << "i`m the most handsome!" << std::endl;
        }
};

template<class T, int N> 
void boyInitial(T (&boy)[N]){
    int i;
    for(i=0;i<N;i++){
        std::cout << "please input boy No." << i+1 << "`s age" << std::endl;
        std::cin >> boy[i].age; 
    }
}

template<class T, int N>
void getBoyAges(T (&boy)[N]){
    int i;
    for(i=0;i<N;i++){
        std::cout << boy.age << std::endl;
    }
}

int main(int argc, char **argv){
    using namespace std;
    int boyNumber = 0;
    cout << "how many boys do you want?" << endl;
    cin >> boyNumber;
    Boy boy[boyNumber];
    boyInitial(boy);
    getBoyAges(boy);
    return 0;
}

描述

我試圖通過引用將男孩類型的數據男孩傳遞給函數 boyInitial() 和 getBoyAges(),然后我得到了這樣的錯誤。

我試圖模仿這里的代碼,然后得到錯誤。 圖像

我很感激你的幫助!

關鍵錯誤信息如下

注意:可變大小的數組類型“long int”不是有效的模板參數

你聲明了一個變長數組(數組的大小不是一個常量表達式)

int boyNumber = 0;
cout << "how many boys do you want?" << endl;
cin >> boyNumber;

Boy boy[boyNumber];

這不是標准的 C++ 功能。

使用標准容器std::vector代替可變長度數組。

所提供的最后一個程序有效,因為沒有可變長度數組。 數組的大小在編譯時是已知的。

至少你可以聲明函數,例如

template<class T> 
void boyInitial(T *boy, size_t n ){
    for( size_t i=0; i < n; i++){
        std::cout << "please input boy No." << i+1 << "`s age" << std::endl;
        std::cin >> boy[i].age; 
    }
}

該函數可以像這樣調用

boyInitial( boy, boyNumber );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM