C++中用户定义的构造函数出现问题

Problems with user defined constructors in C++

本文关键字:问题 构造函数 用户 定义 C++      更新时间:2023-10-16

我对我定义的类构造函数有问题。 我的 .cpp 和 .h 可以自己编译,但是一旦我尝试在 main 中使用它们并构造一个类,它就会抛出错误。

我读过关于没有正确定义用户创建的构造函数可能会导致相同的错误,但我肯定一切都是正确的。

角逐.cpp

#include "joust.h"
2 //create class construct for knight class
3 //set his name stam and put him on a horse
4 knight::knight (string n) :  equipped_wep(5,5,"Basic Blade"){
5   name = n;
6   stamina = 100;
7   mounted = true;
8 }
9 
10 void knight::show_stats() {
11   if (stamina) {
12     cout << name << " is not exhausted (stamina="<< stamina<< ") and is moun    ted" << endl;
13   } else {
14       cout << name <<  " has passed out from exhaustion" << endl;
15   }
16 }
17 void knight::show_wep() {
18   cout << name << " is using " << equipped_wep.display_wep() << endl;
19 }
20 
21 void knight::equip_weapon(weapon wep) {
22   equipped_wep = wep;

角逐

13 #ifndef JOUST_H
14 #define JOUST_H
15 
16 #include <iostream>
17 #include <fstream>
18 #include <vector>
19 
20 using namespace std;
21 
22 class weapon {
23   public:
24     weapon(float = 1, float = 1, string = "base");
25     void set(float, float);
26     string display_wep();
27   private:
28     float effectivness;
29     float weight;
30     string name;
31 };
32 
33 class knight {
34   public:
35     knight( string = "base");
36     void show_stats();
37     void show_wep();
38     void equip_weapon(weapon wep);
39   private:
40     weapon equipped_wep;
41     string name;
42     int stamina;
43     bool mounted;
44 };
45 
46 
47 #endif

测试.cpp

#include "joust.h"
2 
3 int main() {
4   //knight jim("Rob the Third");
5   //jim.show_stats();
6   weapon c(15,12,"jard");
7 
8   return 0;
9 }

生成文件

test: test.o joust.o
2         g++ -std=c++11 joust.o test.o -o test
3 test.o: test.cpp joust.h
4         g++ -std=c++11 test.cpp
5 joust.o: joust.cpp joust.h
6         g++ -std=c++11 -c joust.cpp
7 clean:
8         rm -f joust.o                                                                               

它应该只是创建了一个武器对象半身像,而不是抛出了这个错误

make
g++ -std=c++11 test.cpp
Undefined symbols for architecture x86_64:
"weapon::weapon(float, float, std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >)", referenced from:
_main in test-501f47.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [test.o] Error 1

您有两个问题:

  1. 首先,您需要一起生成所有源文件,或者从随后链接在一起的每个源文件创建对象文件。

  2. 第二个错误是你没有在任何地方定义(实现(weapon构造函数。

第一个问题通过在构建源文件时添加-c标志来解决。-c标志告诉 GCC 创建目标文件(以.o结尾的文件(。您在构建joust.cpp源文件时拥有它,但似乎忘记了test.cpp源文件。

第二个问题应该非常明显地解决:实现构造函数。