返回值类型与函数(指向数组的指针)不匹配

问题描述 投票:0回答:1

我认为我对指针感到困惑,但我可以发誓这些指针匹配..

我的头文件

#ifndef _COMPANY_H
#define _COMPANY_H
#include "Shop.h"
#include <iostream>
#include <string>
#define MAX_SHOPS_NUMBER 10
#define MAX_NAME_LENGTH 10

class Company {
private:
    std::string name;
    Shop* shops[MAX_SHOPS_NUMBER];
    int shopsNumber;
public:
    Company();
    Company(std::string name, Shop* shops[], int shopsNumber);
    std::string getName() const;
    Shop** getShops() ; //problem here
    int getShopsNumber() const;
    void setName(std::string name);
    void setShops(Shop* shops[]);
    void setShopsNumber(int shopsNumber);
    void addShop(Shop* newShop);
    void printShopsByName();
    void printShopsByDay();
    ~Company();
};

#endif

.cpp 文件

#include "Company.h"
#include <iostream>
#include <string>
#define MAX_SHOPS_NUMBER 10
#define MAX_NAME_LENGTH 10

//default c'tor
Company::Company() {
    name = "~";
    Shop s;
    *shops = new Shop[MAX_SHOPS_NUMBER];
    shopsNumber = 0;
}
//c'tor
Company::Company(std::string newName, Shop* shops[], int shopsNumber) {
    if (newName.length() < MAX_NAME_LENGTH) {
        std::cout << "Company name length is too long" << std::endl;
        name = "~";
    }
    *this->shops = *shops; 
    this->shopsNumber = shopsNumber;
}
//d'tor
Company::~Company() {
    delete[] shops;
}
std::string Company::getName() const {
    return name;
}
Shop** Company::getShops() {
    return *shops; //says return value type does not match function 
}


我的 getShops 不断给我错误,唯一不会给我错误的是如果我写了

Shop* Company::getShops() {
    return *shops;

我很确定这是错误的,因为我返回一个指向数组的指针 我尝试将构造中的返回变量类型更改为

shops** shops
而不是
shop* shops[]
,并且我使用了几次语法,但没有其他效果。

c++ pointers
1个回答
0
投票

问题已经从这里开始:

*shops = new Shop[MAX_SHOPS_NUMBER];

您的

shops
变量类型是指针数组,在您的代码中数组已经创建。在构造函数中将其归零而不是
new
就足够了,并且在析构函数中不需要
delete [] shops

for (int i=0; i<MAX_SHOPS_NUMBER; i++) {
  shops[i] = nullptr;
  // or create these objects, based on your logic:  shops[i] = new Shop(...)
}

或者将变量类型

shops
更改为
Shop**
而不是
Shop* shops[MAX_SHOPS_NUMBER]
,但在这种情况下需要创建和准备:

Company::Company() {
   ...
   shops = new Shop[MAX_SHOPS_NUMBER];
   for (int i=0; i<MAX_SHOPS_NUMBER; i++) {
     shops[i] = nullptr;
     // or create these objects, based on your logic:  shops[i] = new Shop(...)
   }
}

Company::~Company() {
    delete[] shops;
}

要返回指针数组的值,不需要取消引用它。只需按原样返回即可,在这两种情况下它都已经是一个指针数组,无论是

Shop**
还是
Shop*[]

Shop** Company::getShops() {
    return shops; 
}
© www.soinside.com 2019 - 2024. All rights reserved.