gpt4 book ai didi

c++ - C++ VSCode无法将 '(classname)'转换为 'int'

转载 作者:行者123 更新时间:2023-12-02 10:26:44 24 4
gpt4 key购买 nike

我编写了一个简单的程序来测试我遇到的错误。即使代码没有问题,也不知道为什么不编译。如果我从A.h文件中删除“include B.h”行,似乎包含的库cos可以解决问题。
main.cpp:

#include "A.h"
#include "B.h"

int main()
{
A a;
B b;

b.funcion(a);

return 0;
}
啊:
#pragma once
#include "B.h"

class A{};
B.h:
#pragma once
#include "A.h"

class B
{
public:
void funcion(A a);
};
B.cpp:
#include "B.h"

void B::funcion(A a){}
终端输出:
> Executing task: bash -c make <

g++ -c -o src/main.o src/main.cpp
In file included from src/A.h:2,
from src/main.cpp:1:
src/B.h:7:18: error: ‘A’ has not been declared
7 | void funcion(A a);
| ^
src/main.cpp: In function ‘int main()’:
src/main.cpp:9:12: error: cannot convert ‘A’ to ‘int’
9 | b.funcion(a);
| ^
| |
| A
In file included from src/A.h:2,
from src/main.cpp:1:
src/B.h:7:20: note: initializing argument 1 of ‘void B::funcion(int)’
7 | void funcion(A a);
| ~~^
make: *** [<integrado>: src/main.o] Error 1
The terminal process "/bin/bash '-c', 'bash -c make'" failed to launch (exit code: 2).

Terminal will be reused by tasks, press any key to close it.
那条消息对我来说毫无意义,任何地方都没有“int”变量。
使用Ubuntu 20.04和Visual Studio Code。
请帮忙。

最佳答案

之所以命名int是因为C++编译器采用了一个它不知道是int的类型。
在头文件中,您必须使用类的正向声明。
C++不处理循环包含。
B.h

#pragma once

class A;

class B
{
public:
void funcion(A a);
};
B.cpp
#include "A.h"
#include "B.h"

void B::funcion(A a){}
不好的做法是按值传递类变量,然后按(const)引用传递它。
B.h
#pragma once

class A;

class B
{
public:
void funcion(const & A a);
};
B.cpp
#include "A.h"
#include "B.h"

void B::funcion(const & A a){}

关于c++ - C++ VSCode无法将 '(classname)'转换为 'int',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64147487/

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