【发布时间】:2021-03-02 03:46:50
【问题描述】:
我正在尝试创建一个函数,它在头文件和 .cpp 文件中的 main.cpp 中返回并在主函数中运行它。
这个过程我在 main 上工作。
#include <iostream>
#include <sstream>
#include "Cards.h"
using namespace std;
//this function returns array
int *function1(){
int a=12;
int b=13;
int c=14;
static int list[3]={a,b,c};
return list;
}
int main(int argc, const char * argv[]) {
int *list;
list=function1();
cout<<list[1]<<endl;
return 0;
}
但是,我不能在标头和单独的 cpp 文件中执行这些操作。
我有一个卡片标题
#ifndef Cards_H
#define Cards_H
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
class Cards{
public:
char suit; //A,H,D,C,S. A is empty card
int number; //00-13
int visibilty;//0 - 1. O invisible 1 is visible
int * function2();
};
#endif
这是类cpp文件
#include "Cards.h"
using namespace std;
//function
int Cards:: function2(){
int a=12;
int b=13;
int c=14;
int list[3]={a,b,c};
return list; // error code Cannot initialize return object of type 'int Cards::*' with an lvalue of type 'int [3]'
}
如何解决这个问题并在 main 中运行它?
【问题讨论】:
-
在
c++中有std::array<int,3>,您可以从函数中返回它。您不能返回 c 数组。相关:https://stackoverflow.com/questions/3473438/return-array-in-a-function -
该代码应该在它看到
int Cards:: array()的那一刻就吐了——标题中的声明表明它返回int *,而不是int。解决这个问题,您仍然会返回一个自动地址,因此您还有很多 UB 需要处理。如果结果是动态的,则使用std::vector<int>,如果是固定的N,则使用std::array<int,N> -
但是,我不能在标头和单独的 cpp 文件中执行这些操作当您从第一个示例移到标头 + 实现示例。话虽如此,如果你总是想返回一个包含 3 个项目的数组,最好只使用正确的 c++ 容器来完成任务,在这种情况下是 std::array
。 -
在你的第二个答案中,
int Cards:: function2(){必须是int* Cards:: function2(){和int list[3]={a,b,c};必须是static int list[3]={a,b,c};但是再次std::array<int,3>更好。您可以像返回 int 一样从函数中返回它。您根本不需要静态部分,也不需要指针。 -
实际上,您的错误看起来好像返回类型是指向成员的指针(
int Cards::*是指向Cards的int成员的指针)。你确定函数签名不是int Cards::* function2(){
标签: c++ arrays function class header