gpt4 book ai didi

c++ - 试图理解类和标题

转载 作者:行者123 更新时间:2023-11-28 02:09:19 25 4
gpt4 key购买 nike

**问题已解决。看来我错误地创建了一个额外的标题,并且由于我删除了他,所以它起作用了。 **

所以我试图了解类和 header 以及如何使它们协同工作。我正在关注在线教程,但我的代码似乎出了问题。问题是,当我尝试运行 main 时,它给了我这个错误:Cat::speak() 和所有其他函数的多重定义。

main.cpp

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

int main()
{
Cat jim;
jim.makehappy();
jim.speak();

Cat george;
george.makesad();
george.speak();

return 0;
}

类.cpp

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

void Cat::speak()
{
if (happy)
{
cout << "meoww" << endl;
}
else
{
cout << "sssss" << endl;
}
}

void Cat::makehappy()
{
happy = true;
}

void Cat::makesad()
{
happy = false;
}

类.h

#ifndef CLASS_H_INCLUDED
#define CLASS_H_INCLUDED

class Cat
{
private:
bool happy;
public:
void makehappy();
void makesad();
void speak();
};

#endif // CLASS_H_INCLUDED

最佳答案

根据您在此处显示的内容,应该没有问题。要暂时解决此问题以查明您是否实际上在多个位置定义此函数,您可以做的是将您的类包装在命名空间中。

class.h

#ifndef CLASS_H_INCLUDED
#define CLASS_H_INCLUDED

namespace myNamespace {

class Cat {
private:
bool happy;
public:
void makehappy();
void makesad();
void speak();
};

} // namespace myNamespace

#endif // CLASS_H_INCLUDED

类.pp

#include <iostream>
#include "class.h"

// using namespace std; // Don't Use - This is Bad Practice
// Can cause name clashing when trying to resolve name lookup


namespace myNamespace {

void Cat::speak() {
if (happy) {
std::cout << "meoww" << std::endl;
} else {
std::cout << "sssss" << std::endl;
}
}

void Cat::makehappy() {
happy = true;
}

void Cat::makesad() {
happy = false;
}

} // namespace myNamespace

main.cpp

#include <iostream>
#include "class.h"
// using namespace std; // Again -Bad Practice

int main() {
using namespace myNamespace;

Cat jim;
jim.makehappy();
jim.speak();

Cat george;
george.makesad();
george.speak();

return 0;
}

试试这个看看你是否遇到同样的编译器错误。这应该有助于您查看是否在多个空间中定义此函数。此外,通过删除 using namespace std; 并仅对 std:: 命名空间使用范围解析运算符将有助于消除任何可能的问题和任何可能的 future 问题。

关于c++ - 试图理解类和标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36313267/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com