0

考虑以下内容:我有两个类(A,B),它们都使用单个头文件(H)。我将 B 预编译为目标文件,然后将 A 编译为调用 B 中的函数的二进制文件。

我现在在头文件中进行更改,然后重新编译 A。这现在会产生垃圾输出。我的问题是,为什么编译器首先允许这种情况发生?

具体示例如下:

猫.h

#include <string>
using namespace std;
class cat_bus;

class catStr {
  private:
    string *a;
  public:
    catStr(string *a)
    {
      this->a = a;
    }
    string chars()
    {
      return a->c_str();
    }
};

class cat {
   friend class cat_bus;
   private:
   catStr a;
   //catStr z; //version X +1
   catStr b;
   catStr c;
   catStr d;
   public :
   cat()
   :a(new string("str1")),
    //z(new string("strz")), //version X +1
    b(new string("str2")),
    c(new string("str3")),
    d(new string("str4"))
  {
  }
};

class cat_bus
{
  private:
    cat myCat;
  public:
    string getA()
    {
      return myCat.a.chars();
    }
    string getB()
    {
      return myCat.b.chars();
 }
    string getC()
    {
      return myCat.c.chars();
    }
};

用户.cpp

#include <iostream>
#include "cat.h"
using namespace std;

void userLibA()
{
   cat_bus catbus;
   cout <<"\nA:"<< catbus.getA() << "\n";
}

void userLibB()
{
   cat_bus catbus;
   cout << "B:"<< catbus.getB()<<"\n";
}

void userLibC()
{
   cat_bus catbus;
   cout << "C:" <<catbus.getC()<<"\n";
}

用户.h

void userLibA();

void userLibB();

void userLibC();

主文件

#include <iostream>
#include "user.h"
#include "cat.h"
using namespace std;
int main ()
{
  userLibA();
  userLibB();
  userLibC();
  cat_bus catbus;
}

STEPS 编译用户:

g++ -c user.cpp

编译主要:

g++ main.cpp user.o

运行主程序:

./a.out

产生:

A:str1
B:str2
C:str3

现在取消注释 cat.h 中的注释。重新编译 main 并运行它。现在产生:

A:str1
B:strz <<<< This line is garbage
C:str3

在我看来,这是直接访问内存位置,链接器不应该按符号名称吗?

4

0 回答 0