我正在尝试完成初学者计算机科学作业。我们刚刚学习空间分配和使用标头,以及动态内存分配。要求之一是我们必须在头中为 const 变量和函数声明使用未命名的名称空间。我在第 28 行收到有关“对匿名名称空间的未定义引用”的编译错误,我不确定如何修复此问题或导致此问题的语法或拼写错误。我们刚刚了解这一点,所以不要太严厉地评判哈哈。
#include <iostream>
#include <memory>
#ifndef MYLIBRARY_HPP
#define MYLIBRARY_HPP
namespace
{
int counter = 0;
const int SIZE = 10;
std::unique_ptr<char[]> deleteRepeats(char arr[]);
}
#endif // MYLIBRARY_HPP
using std::cin;
using std::cout; //using declarations to avoid namespace std
using std::endl;
int main()
{
char originalArray[SIZE]; //declaration of array that will be used in the program and all its values
originalArray [0] = 'a';
originalArray [1] = 'b';
originalArray [2] = 'b';
originalArray [3] = 'c';
originalArray [4] = 'a';
originalArray [5] = 'c';
originalArray [6] = 'a';
originalArray [7] = 'c';
originalArray [8] = 'b';
originalArray [9] = 'c';
std::unique_ptr<char[]> noRepeats = deleteRepeats(originalArray); //function call
cout << "the amount of repeats is... " << SIZE-counter << endl; //prints out the number of repeats
for(int i =0; i<counter; i++) //displays new array
{
cout << noRepeats[i] << endl;
}
return 0;
}
#include <iostream>
#include <memory>
//my function definitions
namespace
{
//Precondition: an array of defined size contains only valid characters
//Postconition: a new array is generated with only unique values
std::unique_ptr<char[]> deleteRepeats(char arr[]) //goes through the array and checks if it has repeats
{
for(int i=0; i<SIZE/2; i++)
{
if(arr[i] = arr[SIZE -1-i]) //marks any repeats
{
arr[i] = '-';
arr[SIZE-1-i] = '-';
}
}
for(int i =0; i<SIZE; i++) //counts new array
{
if(arr[i] != '-')
{
counter++;
}
}
std::unique_ptr<char[]> newArray(new char[counter]); //declares a new array using a pointer
int location = 0;
for(int i = 0; i<SIZE; i++)
{
if(arr[i] != '-')
{
newArray[location++] = arr[i];
}
}
return newArray;
}
}
每次包含标头时,您都会获得一个具有不同秘密名称的new未命名命名空间。
使其“工作”的唯一方法是仅包含它一次,并且仅使用该源文件中的对象。
无法在不同的源文件中引用未命名的命名空间。这就是构建的目的!