【发布时间】:2018-03-02 07:59:26
【问题描述】:
我无法找到解决问题的方法,我认为这与函数重载有关,但我似乎不知道如何解决。
这是我的function.cpp
#include "CountLetter.h"
int Countletter(string sentence, char letter) {
int size = sentence.length();
int toReturn = 0;
for (int i = 0; i<= size; ++i) {
if (sentence[i] == letter) {
toReturn++;
}
}
return toReturn;
}
这是我的函数.h
#ifndef FN_H
#define FN_H
#include <iostream>
using namespace std;
int CountLetter(string sentence, char letter);
#endif
我的 main.cpp
#include "CountLetter.h"
int main() {
string sent = "";
char let = ' ';
int times = 0;
cout << "Enter a sentence.\n";
getline(cin, sent);
cout << "Enter a letter.\n";
cin >> let;
times = CountLetter(sent, let);
cout << "The letter " << let << " occurred " << times << " time(s).\n";
return 0;
}
最后是我的makefile
lab16: lab16.o CountLetter.o
g++ -std=c++11 -o lab16 lab16.o CountLetter.o
lab16.o: lab16.cpp
g++ -std=c++11 -o lab16.o -c lab16.cpp
CountLetter.o: CountLetter.h CountLetter.cpp
g++ -std=c++11 -o CountLetter.o -c CountLetter.cpp
还有我的错误
lab16.o: In function `main':
lab16.cpp:(.text+0xb4): undefined reference to
`CountLetter(std::__cxx11::basic_string<char, std::char_traits<char>,
std::allocator<char> >, char)'
collect2: error: ld returned 1 exit status
Makefile:2: recipe for target 'lab16' failed
make: *** [lab16] Error 1
谢谢!
【问题讨论】:
-
您的文件名称不一致。
lab16.cpp和CountLetter.h是什么? -
CountLetter.o: CountLetter.h(应该只列出标题而不是标题和来源)。function.h发生了什么(失踪??) -
您的
for循环条件i <= size越界导致未定义行为。应该是i < size。
标签: c++ function c++11 compiler-errors