编辑:已回答——问题是因为函数具有相同的签名,尽管它们在不同的文件中,C++ 看到两个版本并感到困惑。
我有三个类:Table
和 Bed
都继承自 Furniture
。
Table
和 Bed
每个类都有一个单独定义的辅助函数 GetLowerCase(std::string)
。当 make
运行时(如下所示的 Makefile),我收到一条错误消息,指出 Bed.cpp
中的 GetLowerCase
是在 Table 中首次定义的.cpp
生成文件:
main: main.o Furniture.o Table.o Bed.o
g++ main.o Furniture.o Table.o Bed.o -o main
main.o: main.cpp
g++ -c main.cpp
Furniture.o: Furniture.cpp Furniture.h
g++ -c Furniture.cpp
Table.o: Furniture.cpp Table.cpp Table.h
g++ -c Table.cpp
Bed.o: Furniture.cpp Bed.cpp Bed.h
g++ -c Bed.cpp
clean:
rm *.o main
表.cpp:
#include "Table.h"
#include <iostream>
#include <string>
std::string GetLowerCase(std::string str)
{
std::string out;
for (int i=0; i<str.length(); i++)
{
out[i] = tolower(str[i]);
}
return out;
}
Table::Table(const std::string n, std::string wt) : Furniture(n)
{
wood_type = GetLowerCase(wt);
if (wood_type != "pine" && wood_type != "oak")
{
std::cerr << "Wood type must be OAK or PINE.";
}
}
void Table::Print()
{
Furniture::Print();
std::cout << "Wood Type: " << wood_type << std::endl;
}
床.cpp:
#include "Bed.h"
#include <iostream>
#include <string>
std::string GetLowerCase(std::string str)
{
std::string out;
for (int i=0; i<str.length(); i++)
{
out[i] = tolower(str[i]);
}
return out;
}
Bed::Bed(const std::string n, std::string sz) : Furniture(n)
{
size = GetLowerCase(sz);
if (size != "twin" && size != "full" && size != "queen" && size != "king")
{
std::cerr << "Bed size must be TWIN, FULL, QUEEN, or KING.";
}
}
void Bed::Print()
{
Furniture::Print();
std::cout << "Size: " << size << std::endl;
}
我原以为 GetLowerCase
会完全包含在定义它的 .cpp
文件中,不会被任何其他文件“看到”。
除了上面列出的两个之外,它不在任何头文件或源文件中。非常困惑,希望得到一些帮助!
最佳答案
声明您的函数static
或将其包装在匿名命名空间中:
namespace {
// duplicated names here.
}
关于C++ 辅助函数的多重定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42126780/