【发布时间】:2016-04-07 14:36:54
【问题描述】:
我对 c++ 很陌生,我真的不明白这个错误是什么或为什么会发生。除了一些未引用的东西外,我没有收到关于为什么它不编译的有用信息。我已经按照在线教程进行了此操作,并且在执行此操作时遇到了其他人没有的错误?也许我不应该使用我找到的教程,你有吗?
反正错误如下:
main.o -> main.cpp:(.text+0x16e): 未定义引用 'validate::set_string(std::string)'
collect2.exe -> [错误] Id 返回 1 个退出状态
Makefile.win -> 目标“Math++.exe”的配方失败
代码如下:
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
string getName();
string name;
class validate {
public:
string item;
void set_string (string);
bool vInput() {
}
bool vName() {
cout << item;
system("pause");
return true;
}
};
int main() {
name = getName();
}
string getName() {
validate val;
cout << "Enter your name: ";
cin >> name;
val.set_string(name);
bool result = val.vName();
return name;
}
我已经尝试移动“validate val;”围绕主要,在所有功能之外,并没有发生任何事情。我还尝试删除 vInput 函数,因为它没有返回,但这也没有任何区别。
在告诉我声明函数的评论后,我尝试这样做,但仍然出现编译错误。我这样声明它们,这对于类可能不正确:
bool vName();
bool vInput();
void set_string (string);
人们试图帮助我后的代码:
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
string getName();
string name;
bool vName();
bool vInput();
void set_string (string);
class validate {
public:
string item;
void set_string (string);
bool vInput() {
return true;
}
bool vName() {
cout << item;
system("pause");
return true;
}
};
int main() {
name = getName();
}
string getName() {
validate val;
cout << "Enter your name: ";
cin >> name;
val.set_string(name);
bool result = val.vName();
return name;
}
似乎没有人明白为什么我的 set_string 什么都不做。好吧,它不应该!我正在关注如何执行此操作的示例,但他们不执行任何功能?
// classes example
#include <iostream>
using namespace std;
class Rectangle {
int width, height;
public:
void set_values (int,int);
int area() {return width*height;}
};
void Rectangle::set_values (int x, int y) {
width = x;
height = y;
}
int main () {
Rectangle rect;
rect.set_values (3,4);
cout << "area: " << rect.area();
return 0;
}
【问题讨论】:
-
您声明了一个函数
void set_string(string),但没有定义它。 -
我没有意识到类中的函数需要定义。并且编译器应该在它到达对它的任何调用之前看到它就在那里?
-
您在
getName()中有val.set_string(name);。如果没有定义set_string函数,编译器会在那里做什么? -
@JohnnyMopp 我在 getName() 之外声明了这些
-
@ForceBru 我觉得 OP 以某种方式相信名称
set_string应该提示编译器需要做什么。这就是我上面的故事。
标签: c++ string validation class input